I expect the following code to work. It compiles (gcc), but the executions gives Segmentation fault: 11. How come? Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_INDEX_LENGTH 20
main()
{
char **indici;
int n = 4;
indici = (char **)malloc(n * sizeof(char*));
int i;
for (i = 0; i < n; i++)
{
indici[i] = (char *)malloc(MAX_INDEX_LENGTH * sizeof(char*));
}
strncpy(indici[0], "aaa", MAX_INDEX_LENGTH);
strncpy(indici[0], "bbbb", MAX_INDEX_LENGTH);
strncpy(indici[0], "ccccc", MAX_INDEX_LENGTH);
strncpy(indici[0], "ddddddd", MAX_INDEX_LENGTH);
for (i = 0; i < n; i++)
{
printf("Index %d is %s\n", n, indici[n]);
}
}
MAX_INDEX_LENGTH * sizeof(char*)instead ofMAX_INDEX_LENGTH * sizeof(char)which is what you actually want I guess.