简体   繁体   English

指针在C中失去价值

[英]Pointer losing value in C

I have a struct which has a char * to act as it's name for finding it. 我有一个struct ,其中有一个char *充当查找它的名称。 I also have an array of struct declared. 我也声明了一个array of struct I am trying to assign a struct a name, but the problem I am having is the char * is continuing to change values to whatever the last name is set. 我正在尝试为结构分配名称,但是我遇到的问题是char *继续将值更改为设置的姓氏。 This is wrecking havoc for the logic of my code. 这严重破坏了我代码的逻辑。 I have tried using malloc() , but that did not change the results. 我尝试使用malloc() ,但这并没有改变结果。

code: 码:

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;
}

I want label to not change with 'X' once the declaration is made, i have tried using malloc() , probably not correctly though. 我希望声明完成后,标签不要用'X'更改,我尝试使用malloc() ,但是可能不正确。

You can do either: 您可以执行以下任一操作:

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

or, if you have strdup() available: 或者,如果您有可用的strdup()

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

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

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