char数组保存最后一个元素

时间:2014-08-16 17:13:50

标签: c arrays pointers

我编写了一个代码来从文件中读取字符串并将它们存储在char数组中。问题是,当我打印先前存储的字符串时,我只是得到数组的每个元素都在while循环的末尾存储了相同的信息。

问题在于数组“ori”和“des”。在while循环之后,我在其中打印信息,但我只是一次又一次地重复最后一个商店。

以下是代码:

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

int main() {

FILE *f;

int sale[31];
int llega[31];
char* ori[31];
char* des[31];
int i;
int j;
char string1 [31];
char string2 [31];
char string3 [31];
char string4 [31];

f=fopen("rol.txt","rt");
i = 0;
while((fscanf(f,"%[^\t]\t%[^\t]\t%[^\t]\t%[^\n]\n", string1, string2, string3, string4 ))!= EOF){

    printf( "%s\t%s\t%s\t%s\n", string1, string2, string3, string4 );
    sale[i] = strtol(string1, NULL, 10);
    llega[i] = strtol(string4, NULL, 10);   

    ori[i] = string2; //Here is where I think I am storing the value of string2
    des[i] = string3; //Here is where I think I am storing the value of string3     
    i++;            
}

for (j = 0; j < 31; j++ ){      
    printf("%s %s %d\n",ori[j],des[j],j); //Here for every "j" I get the same result    
}   
fclose(f);

return 0;
}

1 个答案:

答案 0 :(得分:1)

是。这是一种预期的行为,因为char* ori[31]是一个字符指针数组。声明ori[i] = string2ori[i] = &string2[0]两者都相似)分配string2的地址。因此,所有ori[i]都将包含string2现在拥有的内容(在这种情况下,它是while循环的最后一个赋值)。

使用字符串数组

创建char字符串数组:

char ori[31][31];
char des[31][31];

并指定

strcpy(ori[i], string2);
strcpy(des[i], string3);

或者...

使用std::string (如果您使用的是C ++)

您可以使用:

string ori[31];
string des[31];

ori[i] = string(string2);
des[i] = string(string3);

并打印为printf("%s\t%s\n", ori[j].c_str(), des[j].c_str())

您还需要导入标题<string>