gpt4 book ai didi

c - 循环意外关闭

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:26 24 4
gpt4 key购买 nike

我检查了这个但没有帮助 - For loop scans one less time in c所以,我是编程新手,我试图从 SPOJ 解决这个问题(我的怀疑是普遍的,因此没有在 SPOJ 论坛上发布)。 http://www.spoj.com/problems/STRHH我使用 GCC 在 CodeBlocks 中制作并运行了这段代码,它按预期运行,但当我通过 Ideone 运行它时运行方式不同。

#include<stdio.h>
#include<malloc.h>
#include<string.h>
int main()
{
int n,i,length,j;
char **ptrarray; //creating a pointer array that holds addresses of the strings
fscanf(stdin,"%d",&n);
ptrarray = (int *)malloc(n*sizeof(int)); //dynamically allocating memory for 'n' strings and storing their addresses in 'ptrarray'
for (i=0;i<=n;i++)
ptrarray[i] = (char *)malloc(201); //dynamically allocating memory for the strings
for (i=0;i<=n;i++)
fgets(ptrarray[i],201,stdin); //receiving string
for (i=0;i<=n;i++)
{
length=strlen(ptrarray[i])-1; //string length
for (j=0;j<(length)/2;j+=2) //obtain every other character up to half of the string length
printf("%c",ptrarray[i][j]);
printf("\n");
}
return 0;
}

输入:

4
your
progress
is
noticeable

预期输出:

y
po
i
ntc

所以,当我在 Codeblocks 中运行它时,我得到了预期的输出,但是当它在 ideone 上运行时(并在 SPOJ 上提交),printf 循环只运行三次而不是 4 次,我得到的输出是:

y
po
i

我的问题是为什么我没有在 ideone 中获得第四个“ntc”,为什么它没有被接受?

编辑:将“200”字节更改为“201”字节,使用 fscanf 代替 scanf,删除 fflush 并更新循环条件。因此,如果我将循环条件从 '

最佳答案

这个:

char **ptrarray; //creating a pointer array that holds addresses of the strings  
scanf("%d",&n);
ptrarray = (int *)malloc(n*sizeof(int)); //dynamically allocating memory for 'n' strings and storing their addresses in 'ptrarray'

没有意义;您正在为 n 整数分配空间,但将结果分配给指向指针的指针(一般来说,两者的大小都不与整数相同)。

分配应该是:

ptrarray = malloc(n * sizeof *ptrarray);

这将分配 n 倍于 ptrarray 指向的大小,即 sizeof (char *),但不会重复任何类型名称.

这是一个非常通用且安全得多的模式,值得学习。

如评论中所述,不要fflush(stdin);,这是未定义的行为。

关于c - 循环意外关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47817106/

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