【问题标题】:Structs and functions in CC 中的结构和函数
【发布时间】:2013-10-15 20:25:18
【问题描述】:

我在将结构指针传递给函数时遇到问题,我的代码(简单地说)是

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(&com)'
  • 尝试在编译时启用所有警告(例如 gcc -Wall)。这应该指出问题所在。
  • 顺便说一句,您缺少函数的返回类型。使用gcc -Wall 选项。
  • main(void) 应该是 int main(void)userComFunction(/* ... */) 应该是 void userComFunction(/* ... */)。当你调用userComFunction(com) 时,编译器不知道函数需要什么参数,因为它没有看到它的声明。从 C99 开始,缺少声明是非法的(违反约束);在 C90 中,编译器会对 userComFunction 的外观做出错误的假设。要解决这两个问题,请将userComFunction 的定义移至main 上方,或添加“转发”声明:void userComFunction(struct userCom *return_type);

标签: c struct


【解决方案1】:

正如其他人所指出的,问题在于您将错误类型的参数传递给userComFunction。但真正的问题是你的编译器没有告诉你。

从 C90(这是两个标准之前)开始,调用没有可见声明的函数是合法的,编译器会对函数的实际外观做出假设(通常是不正确的)。当编译器看到对userComFunction 的调用时,它还没有看到userComFunction 的声明或定义,因此它无法诊断您的错误。

从 C99 开始,调用没有可见声明的函数是违反约束,这意味着编译器至少必须警告您。 C99 还删除了“隐式int”规则,因此您不能再在函数声明中省略返回类型; main 应该声明为 int 返回类型(not void!),而 userComFunction,因为它不返回任何内容,所以应该是 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 启用附加警告。

【讨论】:

  • 阅读您的答案时,我总是很想知道。你不会错过任何东西你应该是老师:)
  • @GrijeshChauhan:(-pedantic-errors-pedantic 启用的警告变成致命错误。)这取决于。如果您有将所有警告视为需要修复的问题的策略,那么-pedantic-pedantic-errors 之间没有太大的实际区别。如果您在某些情况下确实需要编写不可移植的代码,并且您确实知道自己在做什么,-pedantic 可以警告您潜在的问题,您可以自行决定是否相应地更改代码。对于尝试编写可移植代码的初学者来说,-pedantic-errors 可能是个好主意。
  • 现在我更清楚了,I had doubt here 所以我问了。
【解决方案2】:

如果你想给 x 赋值 10,那么你应该这样做。 这是正确的代码-

struct userCom{
int x;
int y;
}
void struct userComFunction(struct userCom*);
main(void)
{
struct userCom com;
userComFunction(&com);
printf("%d\n", com.x);
}

userComFunction(struct userCom *return_type){
struct userCom temp;
temp.x = 10;
printf("%d\n", temp.x);
return_type->x= temp.x;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2018-11-05
    • 2020-09-05
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    相关资源
    最近更新 更多