c - 使用 malloc 的指针数组 : The code runs into a segmentation fault. 救命!谢谢

标签 c

看来我有点困惑。与使用指向指针数组的指针一样。如果我可以获取有关该错误的更多信息,我会的。我收到的只是段错误的代码。谢谢:)

查找最长输入字符串的程序。

#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/

相关文章:

c - 循环控制抛出未定义的行为

c - 在文件中搜索字符组合

c - ANSI C 动态内存分配以及何时应该释放内存

c - 如何重置 c 中的链表?

c - header 包含问题

c - 如何改进 printf 各种整数类型的缓冲区大小确定?

c - 为什么使用 char** 会导致 char* 工作时出现段错误?

c - void swap(int *a, int *b) 不适用于数组

for循环中的比较运算符(C语言)

c - 停止自己的进程