下面的代碼和示例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