简体   繁体   中英

*char into main and *char into a struct

The two following codes are similar but the first has a structure, the second not.

Why this code works (with no warnings)?

#include <stdio.h>
#include <string.h>

struct prova
{
    char *stringa;
};

int main()
{
    struct prova p;

    strcpy (p.stringa, "example\0");

    printf("%s\n", p.stringa);

    return 0;
}

But the following code doesn't work?

Segmentation fault (core dumped)

With this warning:

code.c: In function 'main': code.c:8:9: warning: 'stringa' is used uninitialized in this function [-Wuninitialized] strcpy (stringa, "example\\0");

#include <stdio.h>
#include <string.h>

int main()
{
    char *stringa;

    strcpy (stringa, "example\0");

    printf("%s\n", stringa);

    return 0;
}

Thank you!

Neither is correct because you copy to an address specified by an uninitialized variable. Therefore both programs invoke undefined behaviour.

The fact that one of the programs works is down to pure chance. One possible form of undefined behaviour is that your program runs correctly.

You need to initialize the pointer to refer to a sufficiently sized block of memory. For instance:

char *stringa = malloc(8);

Note that you do not need to add a null terminator to a string literal. That is implicit. So, given this memory allocation you can then write:

strcpy(stringa, "example");

You need to give the string some memory for it copy the characters to.

Use malloc

besides the first example does not compile.

When you write

struct prova { char *stringa; };

int main() { struct prova p;

strcpy (p.stringa, "example\0");

notice that p.stringa points to nowhere in particular but you copy to it.

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