Variable increment with pointers

I am very new to working with pointers, and my knowledge of C is pretty small. I am trying to understand pointers. I wrote the following code to print a list of variables (a to f) as follows:

0
1
2
3
4
5

I wrote the following code for this:

#include <stdio.h>
int main(){
  int a,b,c,d,e,f;
  int *p;
  int i;
  a = b = c = d = f = 0;
  p = &a;
  for (i = 0; i < 5; i++){
    *p += i;
    printf("%d\n", *p);
    p++;
  }
  return 0;
}

The idea was that it works through variables and each increases by an ever-increasing number (i). I assume that when variables are initialized at the same time, they will be placed next to each other in memory. However, I get the following output:

0
1
2
3
-1218283607

If I change the for loop only from 0 to 3 (i <4), it works fine, the printer is 0 1 2 and 3. But when I want to print the variable f, it also doesn't seem to have set it.

, , , , - , , .

.

+3
3

, a, b, c, d, e f . , .

#include <stdio.h>
int main() {
    int a[6];
    int *p;
    int i;
    a[0] = a[1] = a[2] = a[3] = a[4] = a[5] = 0;
    p = &a[0];
    for (i = 0; i < 6; i++){
        *p += i;
        p++;
    }
    for(i = 0; i < 6; i++) {
        printf("%d\n", a[i]);
    }
    return 0;
}

int a[6] a, . a[0], a[1], a[2], a[3], a[4] a[5]. , a[0], a[1], a[2], a[3], a[4] a[5] . ,

p = &a[0];

p . .

for , a[i] i i {0, 1, 2, 3, 4, 5}. ,

0
1
2
3 
4
5

.

+9

e. , .

+3

It is unsafe to assume that stack variables are located in memory in any particular order.

You need to use an array, structure, or possibly union, to guarantee the order of your chains.

union {
   int ary[6];
   struct {
      int a;
      int b;
      int c;
      int d;
      int e;
      int f;
      } s;
   } u = {0};

  p = &u.s.a;
  for (i = 0; i < 5; i++){
    *p += i;
    printf("%d\n", *p);
    p++;
  }
+1
source

Source: https://habr.com/ru/post/1728979/


All Articles