Hello Folks,
I have been out of touch with C for a while now. Forgettin some basics. Following code is a simulator of the part of the large code that I am planning to implement. Basically here what it is, i have an array of pointers stored in a structure. I do not know as to how many pointers I will hold this array in the begining. As the code progress I go on adding pointer to the array. I keep a count of how many pointers I added to the array in the structure itself by incrementing it everytime I add a pointer to the array.
Now this is what I am doing (or atleast tryin) in the following code. It's working, but I am not sure if what I am seeing is correct. Can some one help me understand it.
Following is the sample output. My question is why the values of (*p)'' are different than what we are seeing in (*p) and (*p)'.Code:#include <stdio.h> #include <stdlib.h> #include <assert.h> int main() { int **p = NULL; int **top = NULL; char line[50]; int arr[10]; int i,idx; idx = 0; while (1) { printf("Enter a number to store. -1 to end: "); fgets(line,sizeof(line),stdin); sscanf(line,"%d", &i); if (i == -1) break; else arr[idx] = i; if (p == NULL) { p = (int **)malloc(sizeof(int *)); (*p) = (int *)malloc(sizeof(int)); assert (p != NULL && (*p) != NULL); printf("p = %p (*p) = %p\n",p,(*p)); (*p) = &arr[idx]; idx++; top = p; } else { p += (sizeof(int **) + sizeof(int *)); p = (int **)malloc(sizeof(int *)); (*p) = (int *)malloc(sizeof(int)); assert (p != NULL && (*p) != NULL); printf("p' = %p (*p)' = %p\n",p,(*p)); (*p) = &arr[idx]; idx++; } } printf("Entered %d elements\n",idx); for (i=0;i< idx; i++) { printf("p'' = %p (*p)'' = %p arr[%d]: %d\n", top, (*top),i,*(*top)); top = top+ (sizeof(int **) + sizeof(int *)); } return 0; }
BTW, this is an intel PC running Linux and my compiler is gcc.Enter a number to store. -1 to end: 1
p = 0x8049958 (*p) = 0x8049968
Enter a number to store. -1 to end: 2
p' = 0x8049978 (*p)' = 0x8049988
Enter a number to store. -1 to end: 3
p' = 0x8049998 (*p)' = 0x80499a8
Enter a number to store. -1 to end: 4
p' = 0x80499b8 (*p)' = 0x80499c8
Enter a number to store. -1 to end: 5
p' = 0x80499d8 (*p)' = 0x80499e8
Enter a number to store. -1 to end: -1
Entered 5 elements
p'' = 0x8049958 (*p)'' = 0xbfffe7b0 arr[0]: 1
p'' = 0x8049978 (*p)'' = 0xbfffe7b4 arr[1]: 2
p'' = 0x8049998 (*p)'' = 0xbfffe7b8 arr[2]: 3
p'' = 0x80499b8 (*p)'' = 0xbfffe7bc arr[3]: 4
p'' = 0x80499d8 (*p)'' = 0xbfffe7c0 arr[4]: 5
Thanks,