int main()
{
int i=0;
int* p_numbers = ((int*) malloc (5*sizeof(int)));
int* temp;
temp = p_numbers;
for(i=0;i<5;i++)
{
*temp=i;
printf("temp %d p_numbers %d",*temp,*p_numbers);
temp++;
}
}
Please tell that the pointer assigned to temp i.e temp=p_numbers.
DOES temp not point to the same memory position where the p_numbers is pointing to?
you need also to free
p_numberssince otherwise you get a memory leak.also please make a habit of not casting the return value from
mallocbecause in some cases this can cause hard to find errorsexplanation:
the malloc is defined
stdlib.h, if you forget to include that header, themallocfunction will by default assumed to returnintas that is the way in C for functions that have no prototype. Now if you have something likechar*p = (char*)malloc(12);this may cause issues because you effectively casting the returnedintegerto achar*. By explicitly casting you silence the warnings from the compiler and if you have hardware/OS wheresizeof(char*) != sizeof(int)you may get a hard to find error so just writep_numbers = malloc(5*sizeof(int))if you are using a C++ compiler, use
new/deleteinstead.