So, I wrote some code trying to teach myself how to use pointers as 2D arrays a little better, but I'm confused by the output. It should be really simple code - just trying to make a two dimensional array (first value holds pointers to strings, the second is the array of characters that compose the string), then fill it up with values stating what the array index is within each string. Anyway, code is as follows:
Code:
#include <strings.h>
#include <stdlib.h>
int arraysize = 6;
char **myArr;
int
main(int argc, char **argv)
{
myArr = (char**)malloc(arraysize);
int i, j;
for(i = 0; i < arraysize; i++){
myArr[i] = "\n Slotfilled. %d\n", i;
printf(myArr[i]);
}
for(j = 0; j < arraysize; j++){
free(myArr[j]);
}
free(myArr);
exit(0);
}
and what it printed out in the terminal was:
Code:
Slotfilled. 9400308
Slotfilled. 9400308
Slotfilled. 9400308
Slotfilled. 9400308
Slotfilled. 9400308
Slotfilled. 9400308
Segmentation fault
So, why isn't it the numbers 0 through 5? int i isn't even a pointer, so it's not a pointer address, right? Why is it giving me a segmentation fault, am I trying to access something outside of the array?
Also, the values entered into the array change for each time I run it, and is this thing leaking memory?