2012-04-16 123 views
1

我有這樣如何將指針中的值保存到char數組中?

{0 /Data1/ , 0x00, 0, 0xFF}, 

{1 /data2/ , 0x00, 0, 0xFF}, 

{2 /data3/ , 0x00, 0, 0xFF}, 

{3 /data4/ , 0x00, 0, 0xFF}, ... 

我只想打印每行的第二列的數據文件。以下是我工作的代碼。

#include<stdio.h> 
#include<string.h> 
int main() 
{ 
char filename[] = "file.txt"; 
FILE *file = fopen(filename, "r"); 
if(file!= NULL) 
{ 
char line[128]; 
char * word1; 
char word2; 
char word3; 
int i=0; 
clrscr(); 
while (fgets(line, sizeof line, file)!= NULL) 
{ 
i=0; 
word1 = strtok(line, " ,"); 

while(word1!= NULL) 
{ 
i++; 
if(i==2){ 

printf("%s\n",word1); 
} 
word1 = strtok(NULL," ,"); 
} 

} 
fclose(file); 
} 
else 
{ 
perror(filename); 
} 


getch(); 

return 0; 
} 

它工作正常。我可以將每行打印的值保存到數組中嗎? 我想是這樣的

if(i==2){ 
word2 = * (word1); 
} 
printf("%s\n",word1); 

但它給我一個空指針賦值。如何將值打印到數組中?

+0

是否允許使用'std :: vector'而不是數組?代碼是C,但問題標記爲C++。 – hmjd 2012-04-16 19:56:08

+0

相關:http://stackoverflow.com/questions/10179622/how-to-read-second-and-last-words-from-each-line-in-c - 是你編碼的C或C++嗎? – Mat 2012-04-16 19:57:44

+0

我的代碼在C中。在我甚至分手之前,我發佈了相關的問題。現在我只想將每行的指向值保存到數組中以備後用。 – user1336997 2012-04-16 20:00:26

回答

0

您可以使用動態分配的數組,您需要更多的空間才能使用該數組。 有關更多幫助,請參閱Why does a large variable length array has a fixed value -1 even if assigned to in C?

+1

我有問題將char *轉換爲char。我可以讓word2成爲一個數組並保存所有的值,但是問題是如果(i == 2){word2 = *(word1); } printf(「%s \ n」,word1);給我一個空指針分配。分割錯誤。程序異常終止。如何將word1中的值存儲到word2中,這是一個char? – user1336997 2012-04-16 20:16:00

+0

好吧,一個字符串是一個字符數組。當你解析「0x00」時,你得到一個數組爲'{'0','x','0','0','\ 0'}'。至於複製word1到word2,你可以用'strlen'獲得數組的長度'n',然後使用'n + 1'的字節大小的'memcpy'。我認爲你應該做一個關於指針和動態內存的教程來獲得一個好的開始。 – 2012-04-16 20:41:34

1

您只將字符串word1的第一個字符保存到word2中。

如果你想要存儲所有的第二列,你需要分配一個指向動態數組的指針(char *),然後給每個單詞/列分配空間到單詞並複製一個strcpy,因爲word1在每次迭代儘管如此,你不能僅存儲這些信息。

0

嘗試這樣:

#define MAX_BUFFER_SIZE 256 
/* ... */ 

char ** lines = malloc(MAX_BUFFER_SIZE + 1); 
char ** p = lines; 
char ** newbuf; 
int len; 
int bytesloaded = 0; 
int buf_size = MAX_BUFFER_SIZE; 
assert(lines != NULL); 
//... loop etc.. 

if(i==2){ 
    len = strlen(word1); 
    bytesloaded += len; 

    if(bytesloaded >= buf_size) /* Controls buffer size. For avoid buffer overflow/heap corruption/UB. */ 
    { 
     buf_size += MAX_BUFFER_SIZE; 
     newbuf = realloc(lines, buf_size); 

     if(!newbuf) /* return or break. */ 
     { 
     printf("Allocation failed.\n"); 
     free(lines); 
     return 1; 
     } 

     lines = newbuf; 
    } 

    *p++ = word1; /* store the word in lines */ 
    printf("%s\n",word1); 
} 

注意:不要忘了把0終止符,\0,在陣列中,第一圈結束後。

我還沒有測試過這個代碼,但我相信它的工作原理。

這是一個簡單的例子:a dynamic memory allocation,控制它的大小,內存重新分配和值存儲。

相關問題