0

I have the following code:

#include <stdio.h>
#include <stdlib.h>

int *p;

int main() {
    int a = 4, b = 8;

    p = &b;

    //TODO: fill in the blank
    printf("a = %ld\n", /*Fill in here */);
    printf("b = %ld\n", /*Fill in here */);

    return 0;
}

How can I print the value of 2 variables a and b using only p to access them?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Huy Lê
  • 11
  • 2

1 Answers1

1

In general, you cannot do this with current code /approach.

There's nothing in C standard that guarantees the memory allocation strategy for two or more independent variables, so the previous-next memory location tracking is not possible. There's no deterministic way to deduce the value of a, with only access to p.

In case you need to access values of more than one variables (of same type) from a single pointer, consider creating an array, where the elements are guaranteed to reside in contiguous memory location, so pointer arithmetic is meaningful and we can reach the previous-next element deterministically.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Hi, I got the answer. Just using `*(p+1)` for `a` and `*p` for `b`. You can get more information by using google search or reading some books about memory segment =)) Sorry for my bad english. – Huy Lê Feb 22 '17 at 15:44
  • @HuyLê its my duty to inform you that the source of that information should be discontinued immediately, its not correct in general aspect. – Sourav Ghosh Feb 22 '17 at 15:51
  • OK. It's my fault. I'm learning about data segment. And this question only make me understand the mechanism of distributing memory region to allocate the data segment. Its not correct in general aspect as you said. Thank for your help. – Huy Lê Feb 22 '17 at 15:59
  • @HuyLê Pleasure. As I mentioned, you can use arrays to achieve what you want. – Sourav Ghosh Feb 22 '17 at 16:04