2017-06-04 22 views
1

考慮以下幾點:基本鐺:sprintf的復位詮釋計數器爲0

int fileNo = 0; 
sprintf(outfile, "%03d.jpg", fileNo); 

後來

fileNo++; // fileNo equals 1 now 

然後,如果你再次調用此:

sprintf(outfile, "%03d.jpg", fileNo); 

fileNo現在等於0再次。

這裏的目標是保留一個計數器在fileNo,然後將該值傳遞給sprintf以設置文件名。有一種更簡單的方法將計數器轉換爲字符串值嗎?或者我只是錯過了一個步驟,可能會阻止fileNo被重置爲零?

我一直在挖掘到malloc,但它不是很清楚什麼時候這是必要的。幫幫我?

(我沒有新的節目,但新C.)

更新

這是一個非常簡單的程序。沒有重新分配。當我進入調試器時,執行sprintf行後,fileNo立即復位爲0。

...

static int fileNo = 0; 
char outfile[7]; 
sprintf(outfile, "%03d.jpg", fileNo); 

...

while(fread(buffer, 1, 512, inptr) == 512) 
{ 
    // 0xff 0xd8 0xff 
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff) 
    { 
     if (!found1stJPG) 
     { 
      found1stJPG = true; 

     } else { 
      fileNo++; 
      fclose(outptr); 
      sprintf(outfile, "%03d.jpg", fileNo); // fileNo is 1 before this executes 
      printf("outfile: %s,\n", outfile); // in the debugger fileNo is now 0 
     } 
+2

你可能不得不展示更多的代碼,但我懷疑'fileNo'超出了範圍,然後一個新的'fileNo'被實例化爲'0'的值。如果將'int fileNo = 0;'更改爲'static int fileNo = 0;'會發生什麼? – mttrb

+3

'sprintf'不會將計數器重置爲0.您的代碼確實如此。我們看不到的部分。 – Jens

+0

請創建一個[最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve)並向我們展示,否則我們幾乎不可能爲您提供幫助。 –

回答

2

您有以下幾點:

char somecharvariable; 
char outfile[7]; 
int fileNo = 0; 
sprintf(outfile, "%03d.jpg", fileNo); 

哎呀。字符串null結束符寫在fileno上。 outfile應該是長度8.如果你允許fileNo超過999,你的代碼將會崩潰。

將靜態標誌放在fileNo上並不能解決問題。它只是將問題轉移到其他變量。

+0

*'outfile'應該是長度8. *即使這不是一個足夠的修復。 '%03d'格式字符串將導致至少*三個字節被寫入輸出字符串。 –

+0

由於32位整數的十進制表示可能有多達10位數字的符號,所以16將是一個安全值,但由於在這種情況下堆棧空間不太可能受到嚴格限制,因此我建議有一點空間用於維護 - 說32。 – Clifford