我正在创建一个程序,要求用户输入 friend 的数量,然后该程序创建一个指向字符串数组的指针,并根据 friend 的数量分配动态内存,然后要求用户输入姓名他的 friend 的名字,程序将这些名字添加到数组中。 我的问题是,当我获取 friend 的名字时,我的程序崩溃了,并且无法访问数组中的字符串及其字母
我尝试将访问字符串的方式从名称[i]更改为(names + i),但是当我这样做时,我无法访问字符串的字母。
int num_of_friends = 0;
char** names = { 0 };
int i = 0;
// Getting from the user the number of friends
printf("Enter number of friends: ");
scanf("%d", &num_of_friends);
getchar();
// Allocating dynamic memory for the friends's names
names = (char*)malloc(sizeof(char*) * num_of_friends);
// Getting the friends's names
for (i = 0; i < num_of_friends; i++)
{
printf("Enter name of friend %d: ", i + 1);
fgets(names[i], DEFAULT, stdin);
// Removing the \n from the end of the string
names[i][strlen(names[i]) - 1] = '\0';
}
// Just a test to see if it prints the first string
printf("Name: %s\n", names[0]);
我希望输出是数组中的字符串,末尾也没有\n。
最佳答案
您已为 names
分配了内存,其大小等于 char *
的大小乘以 num_of_friends
的数量。因此,您分配了 names[0]
到 names[num_of_friends-1]
元素。
但是,names[i]
并未指向任何有效的内存块。就像names
一样,您需要为每个names[i]
分配内存。
类似于
for (i = 0; i < num_of_friends; i++)
{
names[i] = malloc(DEFAULT);
assert(names[i]); // check against failure
}
在您可以期望写入它们之前,例如
for (i = 0; i < num_of_friends; i++)
{
printf("Enter name of friend %d: ", i + 1);
fgets(names[i], DEFAULT, stdin);
// Removing the \n from the end of the string
names[i][strlen(names[i]) - 1] = '\0';
}
关于c - 字符串分配给指针字符串数组和动态内存的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55708955/