walkerlala
walkerlala

Reputation: 1680

Array behave differently in the main function and outside the main function?

I want to see what will happen when I put some data more than the array can hold in the array. But things differ when I declare the array in the main function and outside the function.

code:

#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;
}

And the result of this program is:

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

So I change the program a little bit, just putting the declaration of the array inside the main program

#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;
}

And the output is differnt:

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

I know this maybe because that one is in the stack and the other is in the heap or so. But I wonder, will the result be the same everytime? I have do some test on other compiler. The result is the same for the first program. But I wonder if it is just so happen, arbitrarily.

And question two is: if it is not arbitrary, then why would the compile truncate the data I input before putting in in the array in the first program, but not in the second program.

Upvotes: 1

Views: 101

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

In both of your examples, you are trying to access the content after the end of the array arr, which is undefined behavior.

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

Not really, in the second example, arr is in the stack, while in the first example, arr is in the static storage, not the heap.

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

No, as explained, it's undefined behavior, the result could be anything.

Upvotes: 3

Related Questions