I need to create a dynamic array of strings of same length. User first enters the string length, and then inputs as many strings as it wants. This is what I've done so far:
printf("Insert string length parameter:\n");
if (scanf("%d", &k) == 0) {
printf("Error in parameter read!");
exit(EXIT_FAILURE);
}
char buffer[k+1];
char **dictionary = malloc(sizeof(char*)); //how to allocate enough pointers to str when n° of strs is unkn?
printf("Insert string sequence (allowed chars: a-Z, - e _):\n");
scanf("%s", buffer);
while(strcmp(buffer, "+exit") != 0) {
if ((dictionary[words] = malloc(k * sizeof(char) + 1)) == NULL) {
printf("Memory allocation error!");
exit(EXIT_FAILURE);
}
strcpy(dictionary[words], buffer);
words++;
scanf("%s", buffer);
}
for (i = 0; i < words; i++)
printf("%s\n", dictionary[i]);
My idea is to create an array of pointers to each string. First user inputs the string, then I allocate memory for it and lastly I copy the string from the buffer to the allocated memory. The issue is that the memory behaves weirdly, I can for example set k to 3 and input a string 10 chars long and it would still work. However, if I enter some inputs of the correct length, the first ones get corrupted or something. For example, with k = 3, the series of inputs:
abc
def
ghi
jkl
mno
pqr
+exit
results in:
¶F☼
☻
def
ghi
jkl
mno
pqr
Any suggestion on why this happens? Thanks a lot to whoever helps me, it's really appreciated!