I am a beginner in C programming. I was recently taught how to use malloc
, but I don't think that I quite understand it. Like why does it need a void *
or any typecast as a matter of fact? Why does the syntax itself have (void *)
in void *malloc(size_t size)
. And how does the variable assigned the malloc
function know where the memory block begins from? Does the malloc
function return an address or something after it has assigned a memory block?
In the class our prof gave us this program. I understand how 2d memory allocation works too.
#include<stdio.h>
#include<conio.h>
void main(void)
{
int *studentInfo=NULL,i=1,j=10,k=0,l=0;
//int *studInfo[10];
int memLoc=0;
clrscr();
printf("How many Student Information You want to store:");
scanf("%d",&j);
printf("How many Subject Marks per student You want to store:");
scanf("%d",&k);
studentInfo=(int *)malloc(j*k*sizeof(int));
//memLoc=0;
for(l=0;l<j;l++)
{
printf("Enter Marks for %dth Student",l+1);
for(i=0;i<k;i++)
{
printf("\nEnter Marks for Subject %d:",i+1);
scanf("%d",studentInfo+(l*j)+i);
}
}
//3 students and 3 subjects
//memory allocated=3*3*2=18
//0,1,2 student 0*no of students
//3 4 5 student 1
//6 7 8 student 2
printf("\nInformation you Entered\n");
for(l=0;l<j;l++)
{
printf("Makrs of Student %d:",l+1);
for(i=0;i<k;i++)
printf("\t%d",*(studentInfo+(l*j)+i));
printf("\n");
}
//*(studentInfo)=10;
//*(studentInfo+1)=20;
//*(studentInfo+2)=30;
//printf("%d\n",sizeof(studentInfo));
//printf("%d\n",*(studentInfo));
//printf("%d\n",*(studentInfo+i++));
//printf("%d\n",*(studentInfo+i++));
free(studentInfo);
getch();
}
In this we are assigning the studentInfo
pointer the malloc function right? So... how does studentInfo
know that the address of the memory block is USA and not Antarctica?? And I know that it is not a good practise to typecast malloc with some other datatype. But why (int *)
. Why does malloc need a pointer?? If malloc needs a pointer that means that it is returning an address right? I asked this to my friend and he said no malloc doesn't return anything. And one more thing is it necessary that we need the typecast to be in brackets?
Please explain in very simple terms. Thank you.