gpt4 book ai didi

c - 循环结束条件不起作用 - C

转载 作者:行者123 更新时间:2023-11-30 18:19:10 24 4
gpt4 key购买 nike

我有一个关于动态数组的作业,因此我试图了解它如何与简单的程序一起工作。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int main()
{
int cnt,i=0;
char temp[1001];
char *obj[5];

scanf("%d",cnt);

while(i<cnt){

scanf("%s",temp);
obj[i]=malloc(sizeof(char)*(strlen(temp)+1));
obj[i]=temp;
printf("%s\n",obj[i]);
printf("%d\n",i);
i++;
}

return 0;
}

当我通过从标准输入读取“cnt”等于5时,程序将永远运行,尽管结束条件满足。但是当我通过在程序的一开始(而不是使用 scanf)分配它使“cnt”等于 5 时,程序运行得很好。这可能是什么原因?

最佳答案

这个:

scanf("%d",cnt);

应该是:

/* Always check return value of scanf(),
which returns the number of assignments made,
to ensure the variables have been assigned a value. */
if (scanf("%d",&cnt) == 1)
{
}

scanf()需要地址cnt .

另外:

  • Don't cast result of malloc() .
  • sizeof(char)保证为 1所以可以从malloc()中的空间计算中省略.
  • 检查malloc()的结果以确保内存已分配。
  • free()不管是什么malloc() d.
  • 使用 scanf("%s") 防止缓冲区溢出通过指定要读取的最大字符数,该最大字符数必须比目标缓冲区少 1,以便为终止空字符留出空间。在你的情况下scanf("%1000s", temp) .
  • 对数组的越界访问没有保护 objwhile循环的终止条件是i<cnt但如果cnt > 5将发生越界访问,导致未定义的行为。

这分配了地址 tempobj[i] :

obj[i]=temp;

不复制(并导致内存泄漏)。使用strcpy()相反:

obj[i] = malloc(strlen(temp) +1 );
if (obj[i])
{
strcpy(obj[i], temp);
}

关于c - 循环结束条件不起作用 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16081389/

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