c programming practice examples

Thread Starter

Gajyamadake

Joined Oct 9, 2019
116
Your two examples are the same, passing by reference.
When you reference an array by its name alone, the value is a pointer to the array. You do this in example 9.
I have doubt I don't see where I am passing structure by reference

C:
#include <stdio.h>
struct student
{
    int x;
    int y;
};

// function prototype
void display(struct student point);

int main()
{
    struct student mypoint;
    mypoint.x = 1;
    mypoint.y = 2;

    display(mypoint);   // passing struct as an argument

    return 0;
}

void display(struct student point)   // updated name point instead of mypoint
{
  printf("\n Displaying information\n");
  printf("\n x: %d", point.x);
  printf("\n y: %d", point.y);
}
Look at this source http://www.tutorialdost.com/C-Programming-Tutorial/22-C-Structure-Function.aspx

There is example for Passing Structure by Value
 
Last edited:

MrChips

Joined Oct 2, 2009
19,270
I am from ol' school where you don't pass structure by value. If the structure is large it takes too much space on the stack.
 

djsfantasi

Joined Apr 11, 2010
5,585
I have doubt I don't see where I am passing structure by reference

C:
#include <stdio.h>
struct student
{
    int x;
    int y;
};

// function prototype
void display(struct student point);

int main()
{
    struct student mypoint;
    mypoint.x = 1;
    mypoint.y = 2;

    display(mypoint);   // passing struct as an argument

    return 0;
}

void display(struct student point)   // updated name point instead of mypoint
{
  printf("\n Displaying information\n");
  printf("\n x: %d", point.x);
  printf("\n y: %d", point.y);
}
Look at this source http://www.tutorialdost.com/C-Programming-Tutorial/22-C-Structure-Function.aspx

There is example for Passing Structure by Value
The line
display(mypoint);
passes the structure by reference! It may not be the preferred syntax, which is &mypoint, but the effect is the same.

From Wikipedia, the structure name is a pointer or address of a contiguous block of memory containing the values of the fields therein. The structure can be “accessed via [...] the struct declared name which returns the same address [as the pointer].” Since you are passing the address of the memory block, I consider it passing by reference.

Other opinions?
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
116
I am from ol' school where you don't pass structure by value. If the structure is large it takes too much space on the stack.
@MrChips not a problem

Example : 11 Dynamic memory allocation

We can allocate memory space statically and dynamically I want to understand difference between them (runtime and compile time)and why need to use dynamic memory allocation.

I am allocating memory space statically
Code:
#include <stdio.h>

int main()
{
    int i = 0;

    int p[5];
   
           for(i=0; i < 5; i++)
           {
               printf("static  memory allocation %p \n", &p[i]);
           }

  return 0;
}
static memory allocation 0061FF18
static memory allocation 0061FF1C
static memory allocation 0061FF20
static memory allocation 0061FF24
static memory allocation 0061FF28

I am allocating dynamic memory
Code:
#include <stdio.h>
#include<stdlib.h>
int main()
{
    int i = 0;

    int *p = (int*)malloc(5 * sizeof(int));
   
           for(i=0; i < 5; i++)
           {
               printf("dyanamic memory allocation %p \n", &p[i]);
           }

  return 0;
}
dyanamic memory allocation 006A0DD8
dyanamic memory allocation 006A0DDC
dyanamic memory allocation 006A0DE0
dyanamic memory allocation 006A0DE4
dyanamic memory allocation 006A0DE8
 

MrSoftware

Joined Oct 29, 2013
1,560
A few big reasons immediately come to mind, surely there are others. (1) Sometimes there isn't enough space on the stack for what you need. For example, try to allocate a few GB of int's on the stack and see what happens. On some operating systems this will crash your app. (2) Sometimes you need memory only for a little while. Maybe you're processing photos, once the photo is done you don't need the memory anymore, so you free it back to the pool where it can be used for other things. (3) lots of things are just easier when you can allocate memory as you need it. Growing linked lists, etc..
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
116
I am still confused if we allocate static array it will store to stack and if we allocate dynamic array it will store to heap

so after all we are storing the elements at the memory. I don't understand what's the benefit of dynamic array instead of static array
 

MrSoftware

Joined Oct 29, 2013
1,560
(1) On most platforms stack space is limited, if you run out then bad things are likely to happen to your process.
(2) On all platforms memory is limited, so it's best not to allocate memory unless you're going to use it, and free it when you're done with it, so the memory can remain available for other things.

Some light reading on stack:
 

MrChips

Joined Oct 2, 2009
19,270
Repeated use of dynamic memory allocation results in memory being fragmented. Garbage collection can fail with disastrous results.
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
116
Repeated use of dynamic memory allocation results in memory being fragmented. Garbage collection can fail with disastrous results.
I think I have to take some time to understand the basic. I will back to the discussion dynamic memory location

Example :12 Break statement
I have loop that can run 10 times. when I use break statement to check condition under loop. When condition is true it will leave loop
C:
#include<stdio.h>

int main()
{
    int x;

    for(x=0; x< 10; x++)
    {
        if(2 == 2)  // ()
        {
            printf("\n equal");
              break;   
        }           
    }
 
return 0;
}
equal

Example :13 continuous statement
I have loop that can run 10 times. when I use continue statement to check condition under loop. When condition is true loop will run until the condition is true
C:
#include<stdio.h>

int main()
{
    int x;

    for(x=0; x< 10; x++)
    {
        if(2 == 2)  // ()
        {
            printf("\n equal");
              continue;   
        }           
    }
 
return 0;
}
equal
equal
equal
equal
equal
equal
equal
equal
equal
equal
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
116
Repeated use of dynamic memory allocation results in memory being fragmented. Garbage collection can fail with disastrous results.
I have done some reading for dynamic memory allocation
For example If we want to store 200 values into array so size of array is fixed 200

Now two problem occur

In first case if the number values to be stored is less then the size of array. hence there is wastage of memory
i.e if we have to store 50 value in array space for 150 value values is wasted

In second case program fail if we want to store more values then the size of array
For example if there is need to store 205 values in array program will give error

Did I understand right
 

MrChips

Joined Oct 2, 2009
19,270
Why would you create an array of 200 elements if you only need to store 50?
Why would you create an array of 200 elements and then attempt to store 205?
 

MrChips

Joined Oct 2, 2009
19,270
In your programming examples with break and continue, the use of continue is redundant.

The use of break is bad programming practice.
Use break only in switch - case structure.
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
116
Why would you create an array of 200 elements if you only need to store 50?
Why would you create an array of 200 elements and then attempt to store 205?
For example, if we need to declare a variable to store data of N students,
Therefore we will end up with following declaration

int students[200];

compiler will assign memory for 200 students Now, there are few issues with static declaration.

Memory wastage: If we are providing input of 50 students, then 150 memory space gets wasted and cannot be used for other purposes. We cannot alter memory size once allocated. For an array of size 200, at any stage it is not possible again to input of 205 students.
 

MrChips

Joined Oct 2, 2009
19,270
In an embedded system, the size of the array must be equal to or larger than the total number of elements required. You will use dynamic allocation only if you intend to release the space after the function has been executed, for example in an intermediate calculation.

Memory space is wasted only if you are permanently occupying space that can be used somewhere else. A student database in memory would be statically allocated (for sorting purposes, for example).
 

MrSoftware

Joined Oct 29, 2013
1,560
I have done some reading for dynamic memory allocation
For example If we want to store 200 values into array so size of array is fixed 200

Now two problem occur

In first case if the number values to be stored is less then the size of array. hence there is wastage of memory
i.e if we have to store 50 value in array space for 150 value values is wasted

In second case program fail if we want to store more values then the size of array
For example if there is need to store 205 values in array program will give error

Did I understand right
Your understanding is correct.
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
116
The use of break is bad programming practice.
Use break only in switch - case structure.
I am using break statement in my program
C:
#include <stdio.h>

int main(void)
{
    int LED ;
   
    printf("Which one LED you want to Turn ON : ");
    scanf("%d",&LED);
   
    switch (LED)
    {
    case 1 :
             printf("Turn On First LED \n");
             break;
    case 2 :
             printf("Turn On Second LED \n");
             break;
    case 3 :
             printf(" Turn On Third LED \n");
             break;
    default :
             printf("Enter Valid Task \n");
    }
    return 0;
}
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
116
Memory space is wasted only if you are permanently occupying space that can be used somewhere else.
int students[200]; compiler will assign memory for 200 students

I am allocating memory space dynamically using malloc function.

C:
#include<stdio.h>
#include<stdlib.h>

int main (void)
{
    int i=0; int size;

    int *students = (int *) malloc(size * sizeof (int));

    if (students == NULL)
    {
        printf("Memory not Available \n");
        exit(1);
    }

    printf("Enter Size of students : ");
    scanf (" %d", &size);

    for(i=0; i < size; i++)
    {
         printf("%d \n", ( students + i));
    }
   return 0;
}
Enter Size of students : 5
11735976
11735980
11735984
11735988
11735992

Example 14 : I am trying to use realloc to add more students
C:
#include<stdio.h>
#include<stdlib.h>
int main (void)
{
    int i=0; int size;
 
    int *students = (int *) malloc(size * sizeof (int));
    if (students == NULL)
    {
        printf("Memory not Available \n");
        exit(1);
    }
    printf("Enter Size of students : ");
    scanf (" %d", &size);
    for(i=0; i < size; i++)
    {
         printf("%d \n", ( students + i));
    }  
    printf("Enter Size of students : ");
    scanf (" %d", &size);
    students = (int*) realloc(size * sizeof (int));
    if (students == NULL)
    {
        printf("Memory not Available \n");
        exit(1);
    }
    for(i=0; i < size; i++)
    {
         printf("%d \n", ( students + i));
    }
   return 0;
}
I do not understand below output
In function 'main':
warning: passing argument 1 of 'realloc' makes pointer from integer without a cast [-Wint-conversion]
students = (int*) realloc(size * sizeof (int));
^~~~
c:\include\stdlib.h:486:40: note: expected 'void *' but argument is of type 'unsigned int'
_CRTIMP __cdecl ___NOTHROW void *realloc (void *, size_t);
^~~~~~~
error: too few arguments to function 'realloc'
students = (int*) realloc(size * sizeof (int));
^~~~~~~
In file included from hello.c:2:0:
c:\include\stdlib.h:486:40: note: declared here
_CRTIMP __cdecl ___NOTHROW void *realloc (void *, size_t);
 

djsfantasi

Joined Apr 11, 2010
5,585
The error is simple to identify.

Check your C resource/manual for the syntax of the “realloc” command.

Fixing one error will eliminate several compile errors.
 

Thread Starter

Gajyamadake

Joined Oct 9, 2019
116
The error is simple to identify.
Fixing one error will eliminate several compile errors.
Thanks djsfantasi I have spotted error.
C:
#include<stdio.h>
#include<stdlib.h>
int main (void)
{
    int i=0; int size; int new_size;

    int *students = (int *) malloc(size * sizeof (int));
    if (students == NULL)
    {
        printf("Memory not Available \n");
        exit(1);
    }
    printf("Enter Size of students : ");
    scanf (" %d", &size);
    for(i=0; i < size; i++)
    {
         printf("%d \n", ( students + i));
    }
    printf("Enter Size of students : ");
    scanf (" %d", &new_size);
    int *moreStudents = (int*) realloc(students, new_size * sizeof (int));
 
    if (moreStudents == NULL)
    {
        printf("Memory not Available \n");
        exit(1);
    }
    for(i=0; i < new_size; i++)
    {
         printf("%d \n", (moreStudents + i));
    }
   free(moreStudents);
   return 0;
}
Enter Size of students : 4
12218400
12218404
12218408
12218412

Enter Size of students : 8
12218400
12218404
12218408
12218412
12218416
12218420
12218424
12218428
 
Last edited:

Thread Starter

Gajyamadake

Joined Oct 9, 2019
116
Dynamic memory allocation for structure
Please take a look at below program
Program :1
C:
#include <stdio.h>
#include<stdlib.h>
struct student
{
   int rollNumber;
};

int main(void)
{
   struct student *p;
   int i, noOfstudents;
   printf("Enter number of students: ");
   scanf("%d", &noOfstudents);

   p = (struct student*) malloc (noOfstudents * sizeof(struct student));
   if (p == NULL)
    {
        printf("Memory not Available \n");
        exit(1);
    }

   else
   {
       printf("Memory allocated\n");
 
       for(i = 0; i < noOfstudents; ++i)
       {
         printf("Enter roll number : \n");
         scanf("%d", &(p+i)->rollNumber);
       }

        printf("Show Roll numbers:\n");

      for(i = 0; i < noOfstudents ; i++)
       {
        printf("%d\n",  (p+i)->rollNumber);
       }
   }
   free(p);

   return 0;
}
Enter number of students: 3
Memory allocated
Enter roll number :
1
Enter roll number :
2
Enter roll number :
3
Show Roll numbers:
1
2
3
@MrChips @djsfantasi I need your's help

I understand passing parameters by value and by the address

I want to modify above code. I want to initialize structure member in main and function that can print data member
Program : 2
C:
#include <stdio.h>
#include<stdlib.h>

struct student
{
   int rollNumber;
};
void show(struct node *head)
{
     struct node *q;
     q = head;
     while (q != NULL)
     {
           printf("%d \n",q->rollNumber);    
     }
int main(void)
{
   int i, noOfstudents;
   struct student s1;
   s1.rollNumber = 20;
   
   struct student *p = (struct student*) malloc (noOfstudents * sizeof(struct student));
   if (p == NULL)
    {
        printf("Memory not Available \n");
        exit(1);
    }
    show(&s1);
   }

   return 0;
}

}
 
Last edited:
Top