bob.sacamento bob.sacamento - 3 months ago 8
C Question

Code Fails to Initialize Array of Strings

I'm trying to do something pretty simple: Establish a collection of 10 eight-character strings and assign a simple default value to each one. My code assigns the first string value, but then bombs with a segmentation fault. Code is below. Can anyone see what I am doing wrong?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main() {

char *(names)[8];
int i;
char defstr[] = "none";

*names = malloc(sizeof(char)*8*10);

printf("%s\n",defstr);

printf("defining\n");

for (i=0; i<10; i++) {
strcpy(names[i], defstr);
printf("done with %d, string is %s\n", i, names[i]);
}

printf("now printing\n");

for (i=0; i<10; i++) {
printf("%s\n", names[i]);
}
}


Output is

$> ./a.out
none
defining
Segmentation fault: 11

Answer
char *(names)[8];

declares an array of 8 pointers, the same as

char* names[8];

Then

*names = malloc(sizeof(char)*8*10);

sets the first of those pointers to point at an array of 80 characters. The other 7 pointers are still uninitialized.

You seem to want a pointer to array, which would be

char (*names)[8];

names = malloc(10*sizeof(*names));