user3224177
user3224177

Reputation: 25

Pointers in C syntax error

Code given below illustrates use of pointers as an exercise:

#include<stdio.h>
struct s{
  int *p;
};
int main(){
  struct s v;
  int *a = 5;
  v->p = a;
  printf("%d",v->p);
  return 0;
}

Why is the syntax error:

invalid type argument -> (struct s)

Upvotes: 0

Views: 485

Answers (4)

Kevin
Kevin

Reputation: 2182

The invalid type argument of ‘->’ (have ‘struct s’) error shows up in lines 8 & 9. Both try to reference the struct's elements using v->p. In this instance, you should change v->p to v.p. This is because 'v' has been allocated and is not a pointer.


This is a neat piece of code for playing with pointers. Once you get the v.p compiling, you are going to see some core dump every time you reference 'a'. This is because you are declaring 'a' as a pointer and not allocating any space for the actual integer value. Try adding the following code to see where it goes:

int b = 5;
int* a = &b;
printf("%d\n", b);
printf("%d\n", *a);
printf("%d\n", a);

Upvotes: 2

Eric Lippert
Eric Lippert

Reputation: 660425

As with many questions about C on StackOverflow, you need to go back to the basics.

  • x->y is a concise way to write (*x).y.
  • The * operator takes a pointer and gives you the variable associated with that pointer.

So now the answer to your question is straightforward. v->p = a; means the same thing as (*v).p = a; The * operator on the value of v turns the pointer v into a variable... but v isn't a pointer. It's a struct s. Therefore, this is an error; the * operator can only be applied to things of pointer type.

Upvotes: 3

rullof
rullof

Reputation: 7434

To access a member of a struct object we use the dot . operator.

v.p = a;

When the struct object need to be acceded through a pointer then we use the operator ->.

struct s *vp = &v;

vp->p = a;

Also you're assigning an integer to an pointer

int *a = 5;

which is very dangerous since any try to dereference it leads to a crash.

Upvotes: 2

Chris Dodd
Chris Dodd

Reputation: 126428

You've declared v to NOT be a pointer (struct s v; -- no *), and you're trying to use ->, which only works on pointers. You're also declaring a to be pointer (int *a -- has a *), but you're trying to initialize it with an integer.

Upvotes: 2

Related Questions