简体   繁体   中英

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)

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.

You've declared v to NOT be a pointer ( struct sv; -- 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.

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.

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 vp . 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 vp 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM