出于教学动机,我想构建一个指向整数的指针,并且我从一个指向 typedef 的指针中获取模型(下面 (1) 中的工作示例)但是 (0) 处的示例给出了消息“错误:在 ptr =&a; '=' 标记之前的语法错误我不明白为什么。感谢指正,代码为:
(0)//失败代码
#include <stdio.h>
typedef int *ptr;
int main(){
int a;
ptr =&a; //<-----"error: syntax error before '=' token"
a =2;
printf("%d\an",a);
return 0;
}
(1)//工作代码
#include <stdio.h>
typedef struct sum {
int a,b,c;
} mytype;
int main(){
mytype sum_operation;
mytype *ptr;
ptr = &sum_operation;
(*ptr).a = 1;
(*ptr).b = 3;
(*ptr).c =(*ptr).b + (*ptr).a ;
printf("%d\n",(*ptr).c);
return 0;
}
最佳答案
此语法:
typedef int *ptr;
不是指向 typedef 的指针。您正在定义一个名为 ptr
的新类型,它是一个指向整数的指针。
此语法:
ptr = &a;
相当于:
int* = &a; // error: syntax error before '=' token
这是不正确的,因为您必须指定一个变量名:
ptr myPointer = &a
相当于:
int* myPointer = &a;
关于c - 指向以指向 typedef 类型的指针为模型的整数类型的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21492521/