我如何以適當的方式分配爲strlen(esc)
內存? temp
和str
是char數據類型。的malloc雙數據類型與strlen的
double esc = t1.tv_sec+(t1.tv_usec/1000000.0);
strAll = malloc(strlen(temp) + strlen(str) + strlen(esc) + 1);
我如何以適當的方式分配爲strlen(esc)
內存? temp
和str
是char數據類型。的malloc雙數據類型與strlen的
double esc = t1.tv_sec+(t1.tv_usec/1000000.0);
strAll = malloc(strlen(temp) + strlen(str) + strlen(esc) + 1);
你不能把strlen(esc)
。因爲我相信,編譯器已經告訴你,該參數strlen()
必須char *
,你傳遞一個double
。嘗試第一轉換double
到的char
陣列snprintf()
。
嘗試使用下面的一個,如果你只是想將所有數據保存在一個緩衝區:
的sizeof(ESC)或的sizeof(雙)
如果你想打開ESC成串。否則,我建議在轉換爲字符串時使用固定點格式,例如snprintf(buffer,7,「%03.3f」,esc);
我不認爲這有幫助。這個海報顯然被C弄糊塗了,並且可能想要構建一個動態分配的字符串,其中包含一些浮點指針的十進制表示。 – 2011-12-29 07:25:38
這些會給出變量的字節大小,但意圖大概是從3個部分創建一個字符串,其中一個部分需要是'esc'的字符串表示形式。所以這並沒有什麼幫助,是嗎? – 2011-12-29 07:26:59
使用像vara [30]這樣的固定大小的變量會有什麼好處,是否有任何性能優勢? – 2011-12-29 07:59:55
您的代碼不進行編譯。 strlen
需要一個字符串參數,即指向序列char
(如數組)的指針。
也許你想要的東西,像
char buf[30];
double esc = somedoublefunction();
snprintf (buf, sizeof(buf), "%f", esc);
return strdup(buf);
當然要照顧到後來free
結果指針。
你需要esc
轉換爲字符串,可能與sprintf()
。然後,在使用長度不同於malloc()
:
char buffer[32];
int n = snprintf(buffer, sizeof(buffer), "%.6f", esc);
if (n >= sizeof(buffer))
...handle overlong string problems (bail out)...
char *strAll = malloc(strlen(temp) + strlen(str) + n + 1);
if (strAll == 0)
...handle out of memory problem (bail out)...
sprintf(strAll, "%s%s%s", temp, str, buffer);
(我沒有檢查由sprintf()
返回,因爲「它錯不了」的長度你計算組件串的長度,因此,它會的。如果你決定檢查它,那麼保留參數malloc()
的長度並進行相應的測試。)
ISO/IEC 9899:1999§7.19.6.5「的'snprintf'功能」說:'_The功能snprintf'返回,將已寫入 了'N'已經足夠大,不計算終止空字符的字符數如果發生編碼錯誤,則返回負值 。因此,當且僅當返回值是非負的並且小於'n'時,空終止的輸出已被完全寫入 。它可能是不完整的,'snprintf()'告訴你緩衝區應該有多大才能成功。 – 2011-12-29 07:33:57
你可以使用snprintf找到你需要的長度。傳遞'0'的大小將防止寫入任何字節,並返回它需要的字節數。
size_t length = snprintf(0, 0, "%lf%s%lf", esc, temp, esc) + 1;
strAll = malloc(length);
snprintf(strAll, length, "%lf%s%lf", esc, temp, esc);
'esc'不是字符串。你希望'strlen(esc)'會返回什麼? – 2011-12-29 07:22:50