看来我有点困惑。与使用指向指针数组的指针一样。如果我可以获取有关该错误的更多信息,我会的。我收到的只是段错误的代码。谢谢:)
查找最长输入字符串的程序。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
int main()
{
char **array;
int i, n, *L, maxlen;
printf("Enter the number of strings that you wish to store : ");
scanf("%d", &n);
array=malloc(n*sizeof(char*)); //acquire storage for an array of pointes of size n//
L=malloc(sizeof(int)*n);// for the length array//
for(i=0;i<n;i++)
{
printf("Enter string %d : ", i+1); //sometimes, prints upto this//
gets(array[i]); //sometimes skips the first string input and jumps to the second and stops at the third//
L[i]=strlength(array[i]);
}
maxlen=0;
for(i=0;i<n;i++)
{
if(L[i]>maxlen)
maxlen=L[i];
}
printf("The string(s) with the maximum length with length %d are : ", maxlen);
for(i=0;i<n;i++)
{
if(L[i]==maxlen)
{
printf("\n%s.", array[i]);
}
}
return 0;
}
int strlength(char *array)
{
int j=0;
while(array[j]!='\0')
{
j++;
}
return j;
}
最佳答案
您为指向指针的指针分配了内存,但忘记为单个指针(即字符串)分配内存。
可以修改为,
array=malloc(n*sizeof(char*));
分配内存来存储字符串的所有指针。
和
for( i = 0; i<n; i++)
{
array[i] = malloc(<max length of string>);
}
那么只有您才有分配的内存空间来存储字符串
关于c - 使用 malloc 的指针数组 : The code runs into a segmentation fault. 救命!谢谢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50141195/