char pointer to pointer question
Hi everyone,
I've been playing around with pointer to pointers recently and stumbled upon a weird problem I can't figure out.
Code:
Code:
#include <stdlib.h>
#include <stdio.h>
int main ()
{
char **test;
char *str1 = "string 1";
char *str2 = "string 2";
char *str3 = "string 3";
int i = 0;
test = malloc(3 * sizeof(char *));
test[0] = str1;
test[1] = str2;
test[2] = str3;
while (*test++) {
printf("%d\n",i);
++i;
}
return 0;
}
Compiling with "gcc -O2 -Wall -pedantic -ansi -g test.c -o test" which results in:
0
1
2
3
Even though there are only 3 char pointers assigned, shouldn't it stop if i == 2 ?
Changing the malloc to malloc(4 * sizeof(char *)) seems to be fixing the problem, but that can't be right, making room for four char pointers but only using three?
Also if I'm assigning one, two, four or more char pointers to test it counts correctly. It only fails when assigning 3 pointers to test.
Can someone please point out to me what I'm missing here?
salt shaker