首页 > 解决方案 > 修改结构中的 char *

问题描述

我正在尝试通过遇到一些问题来修改结构中的 char *。

#define MAXLINELENGTH 1000
#define MAXINSTRUCTIONS 65536

struct labelMem {
    char *name;
    int pc;
};

struct labelStr {
    struct labelMem labels[MAXINSTRUCTIONS];
};




while (func(string s) == 0) {
    strncpy(programLabels.labels[labelCounter].name, label, MAXLINELENGTH);
        labelCounter++;
}

我尝试了几种不同的方式将我的结构排列在一个数组中,但每次我在修改我的 char * var 时遇到问题。

任何有关如何解决此问题的想法将不胜感激。

标签: carraysstructcharc-strings

解决方案


没有调用malloc指针实际上并不指向任何东西。

您需要在使用指针之前为其分配内存。您可以将程序更改为

while (func(string s) == 0) {
    // Allocate memory and check for errors
    programLabels.labels[labelCounter].name = malloc (strlen (label) + 1);
    if (!programLabels.labels[labelCounter].name) { /* handle error */ }

    strncpy(programLabels.labels[labelCounter].name, label, MAXLINELENGTH);
    labelCounter++;
}

推荐阅读