下面的代码和示例csv文件。为什么2个不同的字符串在C中具有相同的地址?
我编写的程序是一个csv阅读器。在while循环中,我将文件的行作为字符串获取,然后使用sscanf提取存储在本地变量中的数据。
我有我存储在字符*名称与char *姓2串,但他们碰巧有相同的地址:
Printing description of name:
(char *) name = 0x000000010004da78 "Bob"
Printing description of surname:
(char *) surname = 0x000000010004da78 "Bob
我不明白为什么,因为他们有不同的变量名。
我希望有这个问题的答案,但它不是我的问题:Temporary C strings have same address
我改名的变量和重新生成.exe(使用Xcode的),但问题仍然存在。任何想法为什么发生这个问题?
感谢
代码
void readFileTest(FILE* *pFile, TTest* *pRootTest)
//Reads the content of the file, line by line
{
int count=0;
char string[MAX_SIZE];
TTest *pTestCurrent=NULL, *pPrevious=NULL;
//Reads first line (wich is the label line)
fgets(string, MAX_SIZE, *pFile);
printf("Column labelling : %s\n", string);
//allocating pointer
pTestCurrent=malloc(sizeof(TTest));
pTestCurrent->ID=0;
pTestCurrent->name="";
pTestCurrent->surname="";
pTestCurrent->mean=0.0;
pTestCurrent->pNext=NULL;
pTestCurrent->pPrevious=NULL;
(*pRootTest)=pTestCurrent;
pPrevious=pTestCurrent;
//Extracts data of each line and stores it in a node
while(fgets(string, MAX_SIZE, *pFile)) //reads line by line until the EOF
{
int identification=0;
char* name;
char* surname;
float mean=0.0;
//Counts iterations (lines) in the file
count+=1;
printf("Iteration n°%d\n", count);
//Extracts data of the line in variables
sscanf(string, "%d,%[^,],%[^,],%f", &identification, name, surname, &mean);
//Assign data in variables to node in pTestCurrent
pTestCurrent->ID=identification;
pTestCurrent->name=name;
pTestCurrent->surname=surname;
pTestCurrent->mean=mean;
//Displays data in node
printf("Line content (stored in pTestCurrent) :\nID : %d\nNAME : %s\nSURNAME : %s\nMEAN : %f\n\n", pTestCurrent->ID, pTestCurrent->name, pTestCurrent->surname, pTestCurrent->mean);
if(pTestCurrent==NULL)
{
printf("ERROR : pointer pTestCurrent is NULL, the programm will exit now\n");
EXIT_FAILURE;
}
//Refresh pointer
pTestCurrent->pNext=malloc(sizeof(TTest));
pTestCurrent=pTestCurrent->pNext;
pTestCurrent->pPrevious=pPrevious;
pTestCurrent->pNext=NULL;
pPrevious=pTestCurrent;
}
};
示例文件:
ID,NAME,SURNAME,MEAN
1,Smith,Bob,4.32
2,Mason,Jack,9.21
3,Gabe,John,2.67
由于没有分配内存但已访问,情况更糟。这仅仅是C语言基础知识的不足。 –
如果他继续以这种方式“复制”字符串,初始化它们将无济于事。 – Leeor