简体   繁体   English

在结构中插入数据** C

[英]Insert data in struct** C

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

typedef struct topic
{
    char name[60];
    int QoS;
} topic;

void parseTopics(struct topic **allTopics)
{
    if ((*allTopics = malloc(sizeof(struct topic) * 3)) == NULL)
    {
        return;
    }
    
    for(int i = 0; i < 3; i++)
    {
        strcpy((*allTopics[i]).name, "Topic");
        (*allTopics[i]).QoS=0;
    }
}

int main(void)
{
    topic *allTopics = NULL;
    int count = 0;
    count = parseTopics(&allTopics);
    printf("Topics:\n");
    for (int i = 0; i < count; i++)
    {
        printf("Name: '%s' | QoS: %d\n", allTopics[i].name, allTopics[i].QoS);
    }
    free(allTopics);
    return 0;
}

How to insert data in **struct?如何在**struct中插入数据? I'm trying like described above, but getting segmentation fault on these lines:我正在尝试如上所述,但在这些行上出现分段错误:

    strcpy((*allTopics[i]).name, "Topic");
    (*allTopics[i]).QoS=0;

It's important for me to allocate memory in 'parseTopics' function, because in this function I will get amount of topics to parse.在 'parseTopics' function 中分配 memory 对我来说很重要,因为在这个 function 中我将获得大量要解析的主题。 Thank you in advice.谢谢你的建议。

Problem solved, thanks ScottHunter!问题已解决,感谢 ScottHunter! The problem was that问题是

*allTopics[i]

was being interpreted as被解释为

*(allTopics[i])

instead of代替

(*allTopics)[i]

Fixed code:固定代码:

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

struct topic
{
    char name[60];
    int QoS;
};

const int a = 3;

void parseTopics(struct topic **allTopics)
{
    if ((*allTopics = malloc(sizeof(struct topic) * a)) == NULL)
    {
        return;
    }

    for (int i = 0; i < a; i++)
    {
        strcpy((*allTopics)[i].name, "Topic");
        (*allTopics)[i].QoS = 0;
    }
}

int main(void)
{
    struct topic *allTopics = NULL;
    parseTopics(&allTopics);
    printf("Topics:\n");
    for (int i = 0; i < a; i++)
    {
        printf("Name: '%s' | QoS: %d\n", allTopics[i].name, allTopics[i].QoS);
    }
    free(allTopics);
    return 0;
}

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

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