gpt4 book ai didi

c - 这两个代码之间有什么区别,看起来它们完全相同,但第二个代码导致段错误?

转载 作者:行者123 更新时间:2023-11-30 16:56:08 30 4
gpt4 key购买 nike

我正在尝试从一维数组创建不同的一维数组,每个数组都用空格分隔。我在一个项目中使用它,如果我使用第二个数组,则会对我的代码造成严重问题。即使调试也没有帮助我。这通常旨在将带有空格的语句转换为不同的字符串。第一个代码为我完成了这项工作,但第二个代码是相同的,但导致段错误。

例如输入“这是C程序”输出应该是 “这个” - 必须在 [0] 中, “is” - 必须在 a[1] 中, “C” - 必须在 a[2] 中, “program” - 必须位于 [3] 中。

这是第一个

#include<stdio.h>
#include<stdlib.h>
void gets(char *);
main()
{
char str[100];
char **a;
int i=0,j=0,k=0,count=0,n;
printf("Enter a String : ");
gets(str);
while(str[k])
if(str[k++]==32)
count++;
count=count+1;
printf("%d\n",count);
a=calloc(count,sizeof(char *));
n=count;
for(i=0;i<count;i++)
{
k=0;
a[i]=calloc(1,20);
while((str[j]!=32)&&(str[j]!=0))
{
a[i][k]=str[j];
j++;
k++;
}
j++;
}
for(j=0;j<n;j++)
printf("%s\n",a[j]);
}

这是第二个

#include<stdio.h>
#include<stdlib.h>
void gets(char *);
main()
{
char str[100];
char **a;
int i=0,j=0,k=0,count=0,n;
printf("Enter a String : ");
gets(str);
while(str[k])
if(str[k++]==32)
count++;
count=count+1;
printf("%d\n",count);
a=calloc(count,sizeof(char *));
n=count;
for(i=0;i<count;i++)
a[i]=calloc(1,20);
while(count)
{
while((str[j]!=32)&&(str[j]!=0))
{
a[i][k]=str[j];
j++;
k++;
}
j++;
i++;
k=0;
count--;
}
for(j=0;j<n;j++)
printf("%s\n",a[j]);
}

最佳答案

第二个循环缺少 i 的重新分配。推导者OP之后hint

for(i=0;i<count;i++)    
a[i]=calloc(1,20);

// add
i = 0;

while(count)
{
while((str[j]!=32)&&(str[j]!=0))
{
// i has a value of count without re-assignment.
// This is UB as a[i] is eventually access outside range of a[]
a[i][k]=str[j];
j++;
k++;
}
...

也许还有其他问题?

关于c - 这两个代码之间有什么区别,看起来它们完全相同,但第二个代码导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40046270/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com