简体   繁体   English

为什么我的 char 数组不打印任何内容?

[英]Why does my char array not print anything?

In c I am trying to assign a char array inside a struct with a user provided value, here is my code:在 c 中,我试图用用户提供的值在结构内分配一个 char 数组,这是我的代码:

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

struct person 
{
       char name[20];
       int age;
};

struct person *assign(char arr[], int age) 
{
       struct person *x = malloc(sizeof(struct person));

       x->name[20] = arr[20];
       x->age = 21;

       return x;
}


int main()
{

     char name[20] = "Arthur morgan";
     int age = 34;

     struct person* person1 = assign(name, age);

     printf("name: %s\n", person1->name);
     printf("age: %d\n", person1->age);


     return 0;
}

The problem is that the name prints nothing for some reason, the age however prints as expected.问题是name由于某种原因没有打印,但年龄却按预期打印。

Why is the name not printing correctly?为什么name打印不正确?

x->name[20] = arr[20];
  1. It does not copy the array它不复制数组
  2. It copies 1 character and you are accessing array outside its bounds which is undefined behaviour (UB)它复制 1 个字符,并且您正在访问其边界之外的数组,这是未定义的行为 (UB)
  3. It is better to use objects not types in sizeof最好使用对象而不是sizeof中的类型
  4. Always check the result of malloc始终检查malloc的结果

You need to copy the string using strcpy function您需要使用strcpy function 复制字符串

struct person *assign(char arr[], int age) 
{
    struct person *x = malloc(sizeof(*x));
    if(x)
    {
        strcpy(x->name,arr);
        x->age = 21;
    }

    return x;
}

https://godbolt.org/z/vKddb4b9a https://godbolt.org/z/vKddb4b9a

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

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