编程新手,结构和功能问题



嘿,我是编程新手(通过 C 语言中的 cs50x 学习),当他们提到结构时,我决定尝试胡闹,只是编写一个快速程序,使用函数交换结构中的一些值。我正在运行,直到出现几条错误消息,其中第一条是"将'结构号*'传递给'结构号*'类型的参数的不兼容指针类型。函数定义中似乎出现了另一个问题,编译器说"'结构号'类型的定义不完整"我只是希望得到一些帮助,因为我被难住了。

这是代码(我知道它很粗糙,但我正在学习哈哈)

#include <stdio.h>
struct numbers;
void swap(struct numbers* s);
int main(void)
{
    struct numbers
    {
        int a;
        int b;
        int c;
    };
    struct numbers x = {1, 5 , 9};
    swap(&x);
    printf("%i, %i, %in", x.a, x.b, x.c);
    return 0;
}
void swap(struct numbers* s)
{
    int temp = s -> a;
    int temp2 = s -> b;
    s -> a = s -> c;
    s -> b = temp;
    s -> c = temp2;
}

您希望swap()中的代码能够访问struct numbers的字段,但该类型的完整声明在main() ,因此不可见。

打破声明,它必须对所有需要它的人可见。将其放在首位也将消除预先声明结构的需要。

swap()本身也是如此,将其放在main()之前将消除在同一文件中为其提供原型的需要。

它应该是:

struct numbers
{
 .
 .
 .
}
static void swap(struct numbers *s)
{
 .
 .
 .
}
int main(void)
{
 .
 .
 .
}

问题是struct numbers声明是全局的,但定义main中是局部的,要使用结构的成员,swap函数必须知道结构具有哪些成员,并且由于它看不到定义它不知道这一点。删除声明并将定义放在全局范围内。

函数swap看不到struct numbers的定义。将其全局置于main之外。

额外提示 - 将typedef与结构一起使用,它使您可以灵活地声明:

typedef struct typeNumbers
{
    int a;
    int b;
    int c;
} numbers;

请注意,typeNumbers 是可选的。声明如下:

numbers x = {1, 2, 3};

问题是结构是主要的,我也对代码进行了一些修复并对其进行了注释。

#include <stdio.h>
//By defining the struct at the beginning you can avoid the forward declaration 
//and it make more sense to know what "numbers" is before continuing reading the code.
struct numbers {
    int a;
    int b;
    int c;
};
void swap(struct numbers* s)
{
    //Small change to use only one temp variable...
    int temp2 = s -> b;
    s -> b = s -> a;
    s -> a = s -> c;
    s -> c = temp2;
}
int main(void)
{
    struct numbers x = {1, 5 , 9};
    swap(&x);
    printf("%i, %i, %in", x.a, x.b, x.c);
    return 0;
}

最新更新