[英]How to add null terminator to char pointer, when using strcpy
我有一個試圖使用strcpy()
函數的程序。 我知道當使用char數組時,例如: char array[10]
,可以通過以下方式設置空終止符: array[0] = '\\0';
但是,在使用char指針時,如何設置空終止符?
編輯:程序編譯,但將垃圾作為輸出
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *target;
char *src = "Test";
target = malloc(sizeof(char));
src = malloc(sizeof(char));
strcpy(target,src);
printf("%c\n",target);
return 0;
}
不用了 strcpy()
第二個參數需要以nul
終止,第一個參數需要適合source + nul
終止符中的字符數。
您的代碼中的問題是:
您以錯誤的方式使用sizeof
運算符,並且通過再次為其分配內存來覆蓋src
指針。
要獲取字符串的長度,您需要strlen()
,而無需在每個指針上調用malloc()
。
由於src
指向新分配的空間,因此您正在從未初始化的數據進行復制,因此您獲得了垃圾值,原因是
src = malloc(sizeof(char));
你不應該那樣做。
sizeof(char) == 1
按定義),因此您只為1個字節分配空間,如果它是有效的C字符串,則必須為'\\0'
因為只能容納1個字符。
字符串的正確printf()
說明符是"%s"
,您正在使用用於字符的"%c"
。
正確的方法是
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *target;
const char *src;
src = "Test"; /* point to a static string literal */
target = malloc(1 + strlen(src)); /* allocate space for the copy of the string */
if (target == NULL) /* check that nothing special happened to prevent tragedy */
return -1;
strcpy(target, src);
printf("%s\n", target);
/* don't forget to free the malloced pointer */
free(target);
return 0;
}
在你的代碼中
strcpy(target,src);
src
不是以null結尾的。 這會調用未定義的行為。
另外,通過使用malloc(sizeof(char));
您只為單個char
元素分配內存。 這可能是您不想要的。
接下來,按照strcpy()
的手冊頁 ,(強調我的)
strcpy()
函數將src
指向的字符串( 包括終止的空字節('\\0'
)strcpy()
復制到dest
指向的緩沖區。 這些字符串可能不會重疊,並且目標字符串dest
必須足夠大才能接收副本 。
所以,只要
你很好。 所以,你必須
src
數組。 target
以便可以容納src
的包含。 最后,要提及的是,一旦使用了字符串,就應該將%s
格式說明符與printf()
以打印字符串。
target = malloc(10);
有內存來容納字符串和nul終止符。 我不明白為什么要為src
分配內存,因為我看到您正在使用字符串文字。 只需為目標分配足夠的內存,並執行strcpy()
來確保您沒有寫超出范圍的數組。
正確的方法是
target = malloc((strlen(src) + 1));
請注意,當您這樣做時
char *src = "Test";
字符串"Test"
存儲在只讀位置,並且該位置的地址返回到src
。 因此,您的字符串已經在內存中,無需為此嘗試再次分配並錯誤地為其分配內存。 所以擺脫src
的malloc()
man strcpy
描述
strcpy()函數將src指向的字符串(包括終止的空字節('\\ 0'))復制到dest指向的緩沖區。
因此,如果src已經有空終止字節,則不必添加它。
臭蟲
如果strcpy()的目標字符串不夠大,則可能會發生任何事情。
因此:
char *src = "Test"; // 4 chars + '\0'
target = malloc(sizeof(char)); // Space for 1 char
strcpy(target,src); // Woops !
到目前為止,答案已經解決了代碼中的缺陷和明顯的誤解,而不是問題。 可以像數組一樣索引指向內存的指針,因此可以這樣:
char *target = malloc( 10 ) ;
這樣就可以設置元素:
target[0] = '\0' ;
Sourav Ghosh的答案是正確的,但是對於這種特定情況,您應該使用strdup(),因為它可以為您處理內存分配和復制:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
const char *src = "Test"; // You should make this const
char *target = strdup(src); // Duplicate
if (target == NULL) { // Check
return EXIT_FAILURE;
}
printf("%s\n", target);
return EXIT_SUCCESS;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.