我在将结构指针传递给函数时遇到问题,我的代码(简单地说)是
struct userCom{
int x;
int y;
}
main(void){
struct userCom com;
userComFunction(com);
printf("%d", com.x);
}
userComFunction(struct userCom *return_type){
struct userCom temp;
temp.x = 10;
printf("%d", temp.x);
*return_type = temp;
}
它会打印
10
11537460
我是否通过了错误的指针? 我似乎无法弄清楚为什么 com.x 不等于 10
最佳答案
正如其他人所指出的,问题在于您向 userComFunction
传递了错误类型的参数。但真正的问题是你的编译器没有告诉你这一点。
从 C90 开始(这是两个标准之前的标准),调用没有可见声明的函数是合法的,并且编译器会对函数的实际外观做出假设(通常是不正确的)。当编译器看到对 userComFunction
的调用时,它没有看到 userComFunction
的声明或定义,因此无法诊断您的错误。
从 C99 开始,调用没有可见声明的函数是一种违反约束的行为,这意味着编译器至少必须警告您这一点。 C99 还删除了“隐式 int
”规则,因此您不能再在函数声明中省略返回类型; main
应使用 int
返回类型(不是 void
!)和 userComFunction
进行声明code>,因为它不返回任何内容,所以应该是 void
。
您可以将 userComFunction
的完整定义移至 main
的定义之上,也可以将定义保留在原处并添加“前向”声明:
void userComFunction(struct userCom *return_type);
int main(void) {
/* ... */
}
void userComFunction(struct userCom *return_type) {
/* ... */
}
当您这样做时,编译器应该让您知道您的调用:
userComFunction(com);
不正确。 (解决方法是将 com
更改为 &com
。)
您还应该使用 gcc 的命令行选项来启用更多警告。例如:
gcc -std=c99 -pedantic -Wall -Wextra
-std=c99
表示强制执行 ISO C99 规则。 -pedantic
表示要真正执行这些规则。 -Wall
和 -Wextra
启用额外警告。
关于c - C 中的结构体和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19255747/