
Originally Posted by
thmm
Code:
ptr = malloc( 2 * sizeof(*ptr));
Your code and your intention don't match.
Don't you see the problem ?
ptr++; This looses the address of the original pointer.
I get correct value without loop
Code:
#include<stdio.h>
#include<stdlib.h>
int main ()
{
int i;
int *ptr;
ptr = malloc( 3 * sizeof(*ptr));
if( ptr != NULL ) /*Check for failure. */
{
*ptr = 0;
printf("%d \n", *ptr);
printf("%p \n", ptr);
ptr++;
*ptr = 1;
printf("%d \n", *ptr);
printf("%p \n", ptr);
ptr++;
*ptr = 2;
printf("%d \n", *ptr);
printf("%p \n", ptr);
}
free( ptr ); /*Release memory. */
return 0;
}
0
00730D48
1
00730D4C
2
00730D50
I don't know what's wrong with "for" loop in previous program.