c - Setting an Array of Integer Pointers -
i trying set array of integer pointers. programs supposed set pointers @ index point integer of value 2*i. programs should print out pointees of first 5 pointer elements, should 0,2,4,6,8.
for reason getting segmentation fault. tell me why happens , can fix it?
i attempted replace final line " arr[index] = &i; ", not give me segmentation fault still gives me wrong results.
help appreciated, starting off array of pointers.
#include <stdio.h> void setarr (int); int * arr[10]; // array of 10 int pointers int main(int argc, char *argv[]) { int i; setarr(0); setarr(1); setarr(2); setarr(3); setarr(4); for(i=0; i<5;i++) printf("arr [%d] = %d\n", i, *arr[i]); /* should 0, 2, 4, 6, 8 */ return 0; } /* set arr[index], pointer, point integer of value 2*index */ void setarr (int index){ int = 2 * index; * arr[index] = i; }
the problem not allocating memory each item in array points to. line
*arr[index] = i;
will set random memory address (whatever in arr[index]
) value of i
.
what should is:
void setarr(int index) { int *i = malloc(sizeof(int)); // allocate memory value *i = 2 * index; // set value arr[index] = i; // make array slot point @ value }
but need make sure free()
memory later. example, before return 0;
statement in main()
function, put:
for (i = 0; < 5; i++) free(arr[i]);
Comments
Post a Comment