Kenshin
Kenshin

Reputation: 177

Correct pointer arithmetic in C

I am trying to learn pointer manipulation in C, and I am not understanding how part of the code isn't working.

#include <stdio.h>

int main() {
  int *alpha[17];

  *(alpha+4)= 35;
  *(alpha+5)= 35;
  *(alpha+12)= 50;

  printf("%d", *(alpha+4));
  *(alpha+8)=*(alpha+5) + *(alpha+12);

  return 0;
}

Why is the line after the printf not working, and causing a crash, when the previous lines ran perfectly? I am trying to get the 9th value to equal the sum of the 6th and 13th value.

Upvotes: 1

Views: 263

Answers (2)

R Sahu
R Sahu

Reputation: 206737

You have created an array of pointers but have not array of ints. You should use:

int alpha[17];

Upvotes: 0

Gyapti Jain
Gyapti Jain

Reputation: 4106

int *alpha[17]; creates array of pointers.

If you want array of int, use int alpha[17];

Your assignations are succesful because of implicit cast from int to pointer. (I hope you are getting warnings)

Adding two pointers is not only non-sensical, but also not allowed in C. This post covers why adding two pointers is forbidden in C++, but arguiments are applicable to C also.

Upvotes: 6

Related Questions