C 中结构体中的字符串字段

问题描述 投票:0回答:1

当我在C中定义结构体时,我可以为字符串定义

char*
吗?

示例:

struct Patient
{
   char *name;
   struct *App app_time;  
};

然后像这样分配它:

student.name = "yoyo" ;
//(运行时有效)

或者我是否必须将字段名称定义为像

char[20]
这样的字符数组,然后使用 strcpy。

两者有什么不同。

我尝试上面的代码。能够打印和更改名称。我没有尝试从用户那里获取输入(scanf)。

但是我在书上看到不允许在结构体中使用 char * 。 我想知道为什么?

c string struct
1个回答
0
投票

但是我在书中看到不允许在结构中使用 char * 。 想知道为什么吗?

这不是事实。您可以使用任何您想要的类型作为结构成员。

  • char *x;
    不是字符串,只是一个 指针,它可能引用末尾带有空终止字符的 char 数组,这是一个 C 字符串
  • char x[20];
    是一个 20 个字符的数组。它还可以包含 C 字符串
  • "yoyo"
    是一个字符串文字。字符串文字无法修改,因为它会调用未定义的行为。
void foo(void)
{
    char *x = "yoyo";  // - x is a pointer to char referencing string literal
    char y[] = "yoyo"; // - y is an array of 5 chars. During initialization "yoyo" is copied into this array

    char z[20];       // defines unitialized array of 20 chars

    strcpy(z, "yoyo");// copies 5 chars to the array z
    x = y;            // x now is referencing the array y. You can modify this array using this pointer.
}
© www.soinside.com 2019 - 2024. All rights reserved.