Originally Posted by
CsdJohn
i want to ask how does malloc works on an array for instance can i dao this
Code:
p=100;
int array[10];
array = malloc(p * sizeof(int));
If you had actually tried that, you would have found all C compilers reject your code. Using an array as an lvalue (i.e. the left hand side of an assignment) is illegal.
malloc() does not reallocate existing arrays. You use it with a pointer to allocate memory that you can then use as if it is an array. The "as if" in bold reflects the fact a pointer (and the memory allocated for it to point at) is not genuinely an array - it just behaves in a compatible manner.
Once memory has been allocated using malloc(), another call of malloc() does not affect it. realloc() can be used to resize the memory allocated using malloc(). Like malloc(), realloc() cannot be used to resize an array - it can only be used to reallocate memory allocated using malloc() (or calloc())..
Code:
int *x = malloc(10*sizeof(int));
int *temp;
int i;
for (i = 0; i < 10; ++i)
x[i] = i;
x = malloc(100*sizeof(int)); /* x can now be used as if it is an array of 100 ints */
/* The catch is that the memory allocated by the first malloc() call is not released */
for (i = 0; i < 10; ++i)
printf("%d ", x[i]); /* will probably not print out values 0 to 9 */
temp = realloc(x, 1000*sizeof(int));
if (temp == NULL) /* realloc() failed */
{
free(x);
exit(0);
}
for (i = 0; i < 1000; ++i)
x[i] = i;
free(x); /* clean up. Don't use x any more after this statement */