简体   繁体   中英

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)

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

#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. 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.

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 . 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM