gpt4 book ai didi

c - 数组在主函数内和主函数外的行为不同?

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

我想看看当我放入一些超出数组所能容纳的数据时会发生什么。但是当我在主函数中和函数外声明数组时,情况有所不同。

代码:

#include<stdio.h>

char arr[5]="lala"; //I declare the array of 5 outside the main function

int main()
{
scanf("%5s",arr); //first I input the data
printf("%p\n",arr); //the address of the array
printf("%s\n",arr); //the contents of the array

char* ptr=arr+5;
printf("%p\n",ptr); //the address right after the array
printf("%s\n",ptr); //the contents after the array's scope

return 0;
}

这个程序的结果是:

whatisyourname     //this is my input, and the output is below
00409000
whati
00409005
//notice that there is a newline here

所以我稍微改变了程序,只是把数组的声明放在主程序里面

#include<stdio.h>

int main()
{
char arr[5]="lala"; //I declare the array here now
scanf("%5s",arr);
printf("%p\n",arr);
printf("%s\n",arr);

char* ptr=arr+5;
printf("%p\n",ptr);
printf("%s\n",ptr);

return 0;
}

输出不同:

whatisyourname    //my input
0028ff37
whati
0028ff3c
< ( //this is where the different happen

我知道这可能是因为一个在栈中,另一个在堆中。但我想知道,每次结果都会一样吗?我在其他编译器上做了一些测试。 第一个程序的结果相同。但我想知道这是否只是任意发生的。

问题二是:如果它不是任意的,那么为什么编译会截断我在第一个程序中放入数组之前输入的数据,而在第二个程序中却不会。

最佳答案

在您的两个示例中,您都试图访问数组 arr 末尾之后的内容,这是未定义的行为。

I know this maybe because that one is in the stack and the other is in the heap or so.

其实不是,在第二个例子中,arr 在栈中,而在第一个例子中,arr 在静态存储中,而不是堆中。

But I wonder, will the result be the same everytime?

不,正如所解释的,这是未定义的行为,结果可以是任何东西。

关于c - 数组在主函数内和主函数外的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30409376/

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