#inlcude <stdio.h>
#inlcude <stdlib.h>
#inlcude <string.h>
int main() {
char *buff = (char*)malloc(sizeof(char) * 5);
char *str = "abcdefghijklmnopqrstuvwxyz";
memcpy (buff, name, strlen(str));
while(*buff) {
printf("%c" , *buff++);
}
printf("\n");
return 0;
}
此代碼打印整個字符串「abc ... xyz」。但「buff」沒有足夠的內存來保存該字符串。 memcpy()如何工作?它使用realloc()嗎?memcpy()使用realloc()嗎?
+1爲直接問題答案。 – 2011-05-23 04:46:11
我想用這個緩衝區在我的真實應用程序中保存一個字符串。該字符串沒有預定義的長度。它會在程序運行時動態增長(附加一些其他字符串...)。我發現的解決方案是分配一些大內存(〜1KB)。我想知道除此之外是否還有其他解決方案?請幫忙。謝謝。 – shan 2011-05-23 05:02:52
@shan,那麼你可以使用'realloc()'(但不是'memcpy()')來達到這個目的。 – iammilind 2011-05-23 05:17:08