[英]c function returning a pointer to a struct
i'm trying to create a function that returns a pointer to a struct here is the code:我正在尝试创建一个函数,该函数返回指向结构的指针,代码如下:
the struct:结构:
struct Nia{
char NIA[6];
};
the function:功能:
struct Nia * prueba(){
struct Nia *nia = malloc(sizeof(struct Nia)*2);
strcpy(nia[0].NIA,"11111\0");
strcpy(nia[1].NIA,"11112\0");
return nia;
}
main function: (it doesn't print anything but it should print 11111)主要功能:(它不打印任何东西,但它应该打印 11111)
int main(int argc, char** argv) {
struct Nia *nia = prueba();
printf("%s\n",nia[0].NIA);
return (EXIT_SUCCESS);
}
where is the problem?问题出在哪儿? i think i'm implemententing the pointers to the structs properly, isn't it?
我想我正在正确地实现指向结构的指针,不是吗?
it returns a segmentation fault actually.它实际上返回一个分段错误。
thanks in advance!提前致谢!
I compiled and ran the following test.c file on Linux Mint 64 bit using gcc -o test test.c -Wall
我使用
gcc -o test test.c -Wall
在 Linux Mint 64 位上编译并运行了以下 test.c 文件
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct Nia{
char NIA[6];
};
struct Nia * prueba(){
struct Nia *nia = malloc(sizeof(struct Nia)*2);
strcpy(nia[0].NIA,"11111\0");
strcpy(nia[1].NIA,"11112\0");
return nia;
}
int main(int argc, char** argv) {
struct Nia *nia = prueba();
printf("%s\n",nia[0].NIA);
return (EXIT_SUCCESS);
}
it outputs 11111
, and compiles without complaint.它输出
11111
,并且编译没有抱怨。 Honestly, even if I omit the include
d headers, it'll run, albiet with warnings, but your system may be different, so just include them and you should be fine.老实说,即使我省略了
include
d 标头,它也会运行,但会发出警告,但您的系统可能会有所不同,因此只需包含它们,您应该没问题。
Of course, having thought about this some more, this can be problematic if you're using C++ not C , which are not the same language .当然,再考虑一下这个问题,如果您使用的是C++而不是C ,这可能会出现问题,因为C++不是同一种语言。 You see,
g++
will have a problem with you assigning the void*
value that malloc()
returns to a symbol of type Nia*
, whereas gcc
is happy to make the conversion for you.你看,
g++
会在你分配malloc()
返回到Nia*
类型的符号的void*
值时遇到问题,而gcc
很乐意为你进行转换。 A different C++ compiler, which you might be using, may allow you to compile it, but a void
has no members, so the NIA
member may not have been initialized, which results in a segfault when you try to print it.您可能正在使用的不同 C++ 编译器可能允许您编译它,但
void
没有成员,因此NIA
成员可能尚未初始化,这会导致在您尝试打印时出现段错误。 To be absolutely sure, use a debugger and find where the memory access violation occurs.为了绝对确定,请使用调试器并找出发生内存访问冲突的位置。
UPDATE: just ran this in Netbeans on the same system, went fine.更新:刚刚在同一系统上的 Netbeans 中运行它,一切顺利。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.