Saturday, May 22, 2010

Having problems understanding Malloc in C programming language !!?

#include%26lt;stdio.h%26gt;


void main()


{


char *ch;


ch= malloc(10);


}





What is the above program doing ??





ch is a character pointer. But if i am allocating 10 bytes of dynamic allocated memory what does it mean ??





why allocate 10 bytes to a character pointer ??





ps:


help:i am doing data structures.

Having problems understanding Malloc in C programming language !!?
your statement is right about the fact that you are allocating 10 bytes to a character pointer. more specifically, you are allocating 10 bytes and setting the char pointer to the first of the 10 bytes. to allocate memory for one character, what you probably should be doing is:





char *ch;


ch = (char*) malloc( sizeof(char) );





if you wanted an array of 10 characters, you would do:





char** charray = (char**) malloc( sizeof(char)*10 );





remember to free the memory once you are done with it!!!


free(ch);


free(charray);
Reply:malloc() and its derivatives are used to dynamically allocate space on the Heap for specific memory storage needs. In your example, what malloc() is doing is creating space for a character array (i.e. string) of length 10 on the Heap allowing for you to assign values of up to 10 characters into your variable 'ch'. So 'ch' could equal "dog" or "new york" etc. Don't forget to de-allocate this memory once you are done using it. C doesn't have garbage collection or anything similar!
Reply:ch now contains the address of the first character of a string of ten characters. Alternatively, ch now points to the first element of a ten-character array. malloc() allocates memory sequentially, so you could say something like this:





ch=ch+1;





and ch would then point to the second character of the string.


No comments:

Post a Comment