C中指针丢失值
Pointer losing value in C
我有一个 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;
}
我希望标签在声明完成后不随 'X' 改变,我尝试过使用 malloc()
,但可能不正确。
您可以执行以下任一操作:
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);
}
我有一个 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;
}
我希望标签在声明完成后不随 'X' 改变,我尝试过使用 malloc()
,但可能不正确。
您可以执行以下任一操作:
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);
}