Mani
Mani

Reputation: 51

Why are the values same?

I am unable to understand this piece of code. I cannot understand why the values of sx, sa, sy are the same , meaning 42. I understand it has to do somthing with the pointers. If someone could explain

#include <stdio.h> 

static int sx;
static int sa[100];
static int sy;

int main() {
    int *p;
    for(p=&sx; p <=&sx+200; p++) 
    {
        *p = 42;
    }   
    printf("sx = \t%i\n",sx);
    printf("sa[0] = \t%i\n",sa[0]);
    printf("sa[109] = \t%i\n",sa[109]);
    printf("sy = \t%i\n",sy);

    getchar();
}

Upvotes: 0

Views: 71

Answers (3)

Alok Save
Alok Save

Reputation: 206636

You are writing beyond the bounds of a variable and so it is undefined behavior.

for(p=&sx; p <=&sx+200; p++) 
{
    *p = 42;
}   

This code fragment writes beyond the memory which was allocated for sx and causes undefined behavior. Note p is pointer to sx and sx is only a single integer and not an array. The loop iterates and writes beyond the memory which is allocated for sx.

Undefined Behavior does not necessarily mandate a program crash, it simply means that the output of the program can be anything. It might appear to work or not or show some strange results, in simple words any result is possible.

Upvotes: 2

DWilches
DWilches

Reputation: 23055

First, your overwriting memory there. So if you want to play with pointers change this:

for(p=&sx; p <=&sx+200; p++)

to:

for(p=&sx; p <=&sy; p++)

Now, What you're doing there is to overwrite every memory position between sx and sy with the value 42. And it happens that sx, sy and every element of sa are in those memory addresses.

And BTW the code makes assumptions about memory arrangements that may not be true in every computer.

Upvotes: 0

FatalError
FatalError

Reputation: 54621

This code makes the assumption that the memory layout of your static data looks like this:

+----+-----------------------------+----+
| sx | sa .....                    | sy |
+----+-----------------------------+----+

Thus, the array is "bounded" by sx and sy, so that using their addresses as boundaries includes all the elements of sa. In this case also, it's using &sx + 200 which likely covers sa and then quite a bit more (remember, pointer arithmetic is scaled).

Strictly speaking, this is undefined behavior and you can't depend on this. But, that is why it works for you.

Upvotes: 5

Related Questions