【问题标题】:Problems Initializing a Struct at Declare Time Using Char Pointer使用字符指针在声明时初始化结构的问题
【发布时间】:2014-09-04 09:42:57
【问题描述】:

我正在尝试使用 char* 指针声明和初始化一个结构。如果我不做任何事情,编译下面的代码就会失败

thing things[] = {{3,300},{4,*text}};

Linux 在尝试打印时给了我一个核心转储

things[1].detail.text; 

当我做单独的分配时它会起作用

things[1].detail.text = text;


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

int main()
{ 
    char *text = "ABC";
    char *text2;

    typedef struct {
        int counter;
        union 
        {
            int number;
            char *text;         
        } detail;
    } thing;

    thing one;
    thing two;   

    one.counter = 1;   
    one.detail.number = 100;

    two.counter = 2;
    two.detail.text = (char *)malloc(10 * sizeof(char));
    strcpy(two.detail.text, text);

    thing things[] = {{3,300},{4,*text}};
    //things[1].detail.text = text;  

    printf("%d: %d\n%d: %s\n", one.counter, one.detail.number, two.counter, two.detail.text);
    printf("%d: %d\n%d: %s\n", things[0].counter, things[0].detail.number, things[1].counter, things[1].detail.text);


    return 0;
}

任何帮助将不胜感激。

【问题讨论】:

  • 用 -Wall 编译并注意你的警告。

标签: c


【解决方案1】:

使用thing things[] = {{3,300},{4,text}};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    相关资源
    最近更新 更多