2015-09-10 65 views
1

一個二維字符陣列的行是否有posibility來計算2D char陣列的行?金額用C

語境:

我讀出一個CSV文件的名字,我想用它後面的數字來計算。

僞代碼:

int workers = size of the 2d char array (a_name) 

workers = sizeof(a_name)顯然是行不通的。

+0

也許你想'的sizeof(a_name)/的sizeof(* a_name )'? –

+3

如果你閱讀這個文件,應該很容易地跟蹤行數,並且*必要*(你是如何跟蹤數組中的哪一行你會寫每行的?) –

+0

請顯示你的「a_name」聲明以及您創建其上下文的代碼部分。 – lurker

回答

0

在讀取csv文件,你可以指望的工人人數。

2.可以讓編寫一個函數,將計算工人的數量(取決於工人的數量你期待它可能是值得的)。無論如何,如果你要使用strlen,它會遍歷整個事物,直到達到第一個'\ 0'。

它應該是這個樣子

char workers[ MAX_WORKERS ][ MAX_NAME_LENGTH ]; 
int counter; 

// assuming the array was filled from 0 sequntially 
for (counter = 0; counter < MAX_WORKERS; counter++) { 
    if (*(workers[ i ]) == 0) 
     break; 
} 

// counter now holds the number of workers 

另一個可能的解決方案(不知道我這樣做是正確的)

char workers[ MAX_WORKERS ][ MAX_NAME_LENGTH ]; 
char *pointer; 
int counter 

counter = 0; 
pointer = workers; 

// assuming a memset or calloc have been made for workers, and that the array was filled from 0 sequntially 
while(pointer != NULL) { 
    pointer += MAX_NAME_LENGTH; 
    counter++; 
} 

// counter now holds the number of workers 
+0

我想你應該更多地體會到,只有在使用了所有MAX_WORKERS條目的情況下,代碼纔會起作用。 –