我知道这是个简单的问题,但不明白为什么会出错。
请帮助我得到这个非常简单的程序工作。它给出了错误和seg错误,如下所示。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct msgclient
{
    int msglen;
    int msgtype;
    char cp[100];
}M1;

int main()
{
    M1 *m;
    m=malloc(sizeof(M1));
    m->msglen=5;
    m->msgtype=6;
    m->cp="hi how are you";  //error

    printf("\n%d\n%d\n%s",m->msglen,m->msgtype,m->cp);
    return 0;
}

谢谢:)

最佳答案

您需要为结构分配内存

 M1 *m= malloc(sizeof(M1)) ;

并使用strncpy将字符串复制到数组中
 int n = strlen("hi how are you");
 strncpy(m->cp,"hi how are you",n);
 m->cp[n] = '\0';

当您试图将数组的地址分配给数组时,m->cp ="hi how are you";不会编译,这就像编写"hi how are you"

关于c - C linux中包含字符数组作为其成员的结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22557175/

10-11 22:57
查看更多