我希望这个问题有一个简单的答案,所以请耐心等待。如果我有一个 C 头文件这样定义 TYPE:
struct Example {
char description[EXAMPLE_DESC_SIZE];
int val;
};
typedef struct Example Example;
# ifndef TYPE
# define TYPE Example
# define TYPE_SIZE sizeof(Example)
# endif
然后在一个.c文件中,我有一个函数如下:
TYPE createExample (int val, char *desc) {
}
从主函数调用
TYPE newEx;
char desc[EXAMPLE_DESC_SIZE], filename[50], *nlptr;
int val;
newEx = createExample(val, desc);
如何编写 createExample 代码以便它返回 TYPE?我尝试了以下(以及其他一些不成功的尝试):
TYPE createExample (int val, char *desc)
{
TYPE temp;
struct Example example;
example->val = val;
strcpy(example->description, desc);
return temp = example;
}
最佳答案
随着问题的改变,我稍微改变了我的答案:
基本上 TYPE 定义是正确的,代码也是。唯一错误的是在 createExample
中使用了 example
的实例:当您声明堆栈变量时,您不能使用“->”运算符来访问字段。你必须使用 '.'运算符(operator)。因此,对字段 val
的正确访问是通过 example.val = val
。这就是你的编译器通过
'invalid type argument of '->'.
还是
struct Example {
char description[EXAMPLE_DESC_SIZE];
int val;
};
typedef struct Example Example;
可以缩短为
typedef struct Example {
char description[EXAMPLE_DESC_SIZE];
int val;
}Example;
并且您应该考虑按值返回结构是否是个好主意,因为这意味着每次都将它们从堆栈区域复制到堆栈区域。根据结构的大小,这在某些情况下可能会破坏您的堆栈。也许您应该在某个时候考虑动态分配和传递指针。
关于C:创建一个结构,返回一个类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15047205/