我正在尝试制作一个字符数组。程序将读入句子并将句子存储在字符数组中,然后将该字符数组存储在另一个数组中。在阅读了大量的网站和层叠的流动网页后,我认为可以这样做。当试图将我的字符数组存储到另一个数组中时,程序中断,所以我不确定如何更正代码。
#include <stdio.h>
#include <math.h>
#include <time.h>
int main(int ac, char *av[])
{
int size; //number of sentences
char strings[100];// character array to hold the sentences
char temp;
printf("Number of Strings: ");
scanf_s("%d", &size); // read in the number of sentences to type
char **c = malloc(size); //array of character arrays
int i = 0;
int j = 0;
while (i < size) //loop for number of sentences
{
printf("Enter string %i ",(i+1));
scanf_s("%c", &temp); // temp statement to clear buffer
fgets(strings, 100, stdin);
// **** this next line breaks the program
c[i][j] = strings; // store sentence into array of character arrays
j++;
i++;
}
printf("The first character in element 0 is: %d\n", c[0][0]);
system("PAUSE");
return 0;
}
最佳答案
您只需为字符串分配内存即可读取和复制字符串:
c[i][j] = strings; // replace this with:
c[i]= malloc(strlen(strings)+1);
strcpy(c[i],strings);