Unborn - 1 year ago 83

C Question

I'm having trouble understanding what the output would be

`int main( ) {`

int x = 5, y = 10, z = 20;

int *ptr1 = &x, *ptr2 = &y, *ptr3 = &z;

*ptr2 = *ptr3 + *ptr1;

ptr2 = ptr1;

*ptr2 = *ptr3;

printf("%d and %d and %d\n", x,y,z);

/*char str[] = "Stackoverflow is kind.";

int len = strlen(str);

printf("%s and %d\n", str, len);

char *p;

p = str;

printf("%c and %c and %c and %c\n",

*p, str[3], *(p+9), str[len-2]);*/

return 0;

}

Would the first addition line even be allowed? I thought you couldn't add pointers. And what would the difference be between these 2 lines?

`ptr2 = ptr1;`

*ptr2 = *ptr3;

Obviously they are different pointers, but how do they function differently?

I've ran the program and got 20 25 20 but I don't understand how

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

After executing the lines

```
int x = 5, y = 10, z = 20;
int *ptr1 = &x, *ptr2 = &y, *ptr3 = &z;
```

the following conditions are true:

```
ptr1 == &x
*ptr1 == x == 5
ptr2 == &y
*ptr2 == y == 10
ptr3 == &z
*ptr3 == z == 20
```

Thus, the *expression* `*ptr1`

is the same as the *expression* `x`

, `*ptr2`

is the same as `y`

, etc. So the line

```
*ptr2 = *ptr3 + *ptr1;
```

isn't adding the *pointer* values, it's adding the values of the objects the pointers *point to* - IOW, this is equivalent to writing

```
y = x + z;
```

In the line

```
ptr2 = ptr1;
```

you're setting `ptr2`

to same value as `ptr1`

, meaning it will point to the *same object* as `ptr1`

. After this line, the following conditions are all true:

```
ptr2 == ptr1 == &x
*ptr2 == *ptr1 == x == 10
```

Finally, the line

```
*ptr2 = *ptr3;
```

sets the value of the object that `ptr2`

points to (`x`

) to the value of the object that `ptr3`

points to (`z`

); IOW, this is equivalent to writing

```
x = z;
```

So, over the course of the program:

```
y = z + x == 25
x = z == 20
```

hence your output.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**