【问题标题】:structure containing character array as its member in C linuxC linux中包含字符数组作为其成员的结构
【发布时间】:2014-03-21 11:12:08
【问题描述】:

我知道这是一个简单的问题,但不明白为什么会出错。 请帮助我完成这个非常简单的编工作。它在 cmets 中给出如下所示的错误和段错误。

#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 = { 5, 6, "hi how are you"};

标签: c linux struct


【解决方案1】:

你的问题是

M1* m;

m 未初始化,将指向随机内存地址。你需要做的

M1* m = malloc(sizeof(M1));
...
strncpy(m->cp, "hi how are you", 15);
free(m);

【讨论】:

  • @user3436838 因为“hi how are you”是一个 const char* 而 m->cp 是一个数组。
【解决方案2】:

您必须为m 指针分配内存。在您的程序中,m 指针未初始化,它包含垃圾,并且最有可能指向无效内存。

例如:

M1 *m = malloc(sizeof M1) ;

或者只是不使用如下指针:

M1 m;
m.msglen=5;
m.msgtype=6;
strcpy(m.cp, "hi how are you"); // see also below

其他问题:

m.cp = "hi how are you" ;

m->cp = "hi how are you" ;

不会编译,你需要使用strcpy 函数。 C 中没有真正的字符串类型,因为它存在于其他语言中。

【讨论】:

  • 您不能将字符串文字分配给cp
  • 非常感谢@Michael
【解决方案3】:

你需要为你的结构分配内存

 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-&gt;cp ="hi how are you"; 无法编译,因为您尝试将数组"hi how are you" 的地址分配给数组cp,就像写&amp;m-&gt;cp[0] = &amp;"hi how are you"[0]; 一样

【讨论】:

  • 感谢它的工作。我主要关心字符串部分。现在很清楚了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多