指针在C中失去价值

时间:2015-04-20 02:57:01

标签: c pointers struct char

我有一个struct,其中char *可以作为查找它的名称。我也声明了array of struct。我正在尝试为结构分配一个名称,但我遇到的问题是char *继续将值更改为设置的姓氏。这对我的代码逻辑造成了严重破坏。我尝试过使用malloc(),但这并没有改变结果。

代码:

struct foo {
       char* label;
}
typedef struct foo fum;
fum foolist[25];
/*initialize all elements in foo list to be "empty"*/
bool setArray(char* X) {
      for(int i =0; i <25;i++) {
           if(strncmp("empty", foolist[i].label,5*sizeof(char))==0) {
                    //tried char* temp = (char*)malloc(32*sizeof(char));
                    //foolist[i].label = temp; no change.
                    foolist[i].label = X;
                    return true;
           }
      }
      return false;
}

我希望标签不会随着&#39; X&#39;而改变。一旦声明,我尝试使用malloc(),但可能不正确。

1 个答案:

答案 0 :(得分:2)

你可以这样做:

foolist[i].label = malloc(strlen(X) + 1);
if ( !foolist[i].label ) {
    perror("couldn't allocate memory"):
    exit(EXIT_FAILURE);
}
strcpy(foolist[i].label, X);

或者,如果您有strdup()可用:

foolist[i].label = strdup(X);
if ( !foolist[i].label ) {
    perror("couldn't allocate memory"):
    exit(EXIT_FAILURE);
}
相关问题