简体   繁体   English

C语法错误的指针

[英]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. 与StackOverflow上有关C的许多问题一样,您需要回到基础知识。

  • x->y is a concise way to write (*x).y . x->y是编写(*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; (*v).p = a;含义相同(*v).p = a; The * operator on the value of v turns the pointer v into a variable... but v isn't a pointer. v值的*运算符将指针v变成变量...但是v不是指针。 It's a struct s . 这是一个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. 您已将v声明为不是指针( struct sv; * ),并且尝试使用-> ,该方法仅对指针有效。 You're also declaring a to be pointer ( int *a -- has a * ), but you're trying to initialize it with an integer. 您还声明a为指针( int *a具有* ),但是您尝试使用整数对其进行初始化。

To access a member of a struct object we use the dot . 要访问struct对象的成员,我们使用点. operator. 操作员。

v.p = a;

When the struct object need to be acceded through a pointer then we use the operator -> . 当需要通过指针访问struct对象时,我们使用运算符->

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 . invalid type argument of '->' (have 'struct s')错误显示在第8和9行中。两者都尝试使用v->p引用结构的元素。 In this instance, you should change v->p to vp . 在这种情况下,您应该将v->p更改为vp This is because 'v' has been allocated and is not a pointer. 这是因为已经分配了“ v”,它不是指针。


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'. 进行vp编译后,每次引用“ a”时都会看到一些核心转储。 This is because you are declaring 'a' as a pointer and not allocating any space for the actual integer value. 这是因为您将'a'声明为指针,并且没有为实际整数值分配任何空间。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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