数组在主函数和主函数之外的行为有所不同吗?

时间:2015-05-23 05:53:29

标签: c arrays

我想看看当我放置一些数据而不是阵列可以容纳的数据时会发生什么。但是当我在main函数和函数外部声明数组时,情况会有所不同。

代码:

#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

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

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

1 个答案:

答案 0 :(得分:3)

在两个示例中,您都试图在数组res[, time:= format(time, '%d.%m.%Y %H:%M')] # sth time # 1: A 01.01.2014 09:00 # 2: A 01.01.2014 10:00 # 3: A 01.01.2014 11:00 # 4: A 01.01.2014 12:00 # 5: A 01.01.2014 13:00 # 6: A 01.01.2014 14:00 # 7: A 01.01.2014 15:00 # 8: A 01.01.2014 16:00 # 9: A 01.01.2014 17:00 #10: B 01.01.2014 18:00 #11: B 01.01.2014 19:00 #12: 01.01.2014 20:00 #13: 01.01.2014 21:00 #14: 01.01.2014 22:00 #15: 01.01.2014 23:00 #16: 02.01.2014 00:00 #17: 02.01.2014 01:00 #18: 02.01.2014 02:00 #19: 02.01.2014 03:00 #20: 02.01.2014 04:00 #21: 02.01.2014 05:00 #22: 02.01.2014 06:00 #23: 02.01.2014 07:00 #24: C 02.01.2014 08:00 #25: C 02.01.2014 09:00 #26: C 02.01.2014 10:00 #27: C 02.01.2014 11:00 # sth time 结束后访问内容,这是未定义的行为。

  

我知道这可能是因为那个在堆栈中而另一个在堆中。

实际上,在第二个示例中,arr位于堆栈中,而在第一个示例中,arr位于静态存储中,而不是堆中。

  

但我想知道,每次结果都是一样的吗?

不,正如所解释的,它的未定义行为,结果可能是任何结果。

相关问题