简体   繁体   English

* char成为main和* char成为struct

[英]*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 使用malloc

besides the first example does not compile. 除了第一个示例,不会编译。

When you write 当你写

struct prova { char *stringa; struct prova {char * stringa; }; };

int main() { struct prova p; int main(){struct prova p;

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

notice that p.stringa points to nowhere in particular but you copy to it. 请注意,p.stringa特别指向无处,但您将其复制到该位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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