[英]How to copy string char by char in c?
我在堆上聲明了一塊內存。
char *str;
str = (char *)malloc(sizeof(char) * 10);
我有一個const字符串。
const char *name = "chase";
因為*name
短於10
所以我需要用chase
加5個空格來填充str
。
我試圖循環並設置str[i] = name[i]
但是有些東西我沒有匹配,因為我無法為其他字符分配空格。 這就是我要去的地方,只是嘗試用所有空間填充str
來開始
int i;
for (i = 0; i < 10; i++)
{
strcpy(str[i], ' ');
printf("char: %c\n", str[i]);
}
正如其他人指出的那樣,您需要
//malloc casting is (arguably) bad
str = malloc(sizeof(char) * 11);
然后,做
snprintf(str, 11, "%10s", name);
使用snprintf()
而不是sprintf()
將防止溢出,並且%10s
將根據需要填充結果字符串。
如果希望str
具有10個字符並且仍然是C字符串,則需要'\\0'
終止它。 你可以做到這一點malloc
荷蘭國際集團str
至11的長度:
str = malloc(11);
注意,不需要malloc
的返回指針。 另外, sizeof(char)
始終為1,因此無需將其乘以所需的char
數。
你以后malloc
的內存,因為你需要,你可以使用memset
設置所有char
s到' '
(空格字符)的最后一個元素除外。 最后一個元素必須為'\\0'
:
memset(str, ' ', 10);
str[10] = '\0';
現在,使用memcpy
將const
C字符串復制到str
:
memcpy(str, name, strlen(name));
易於使用的snprintf像這樣
#include <stdio.h>
#include <stdlib.h>
int main(){
char *str;
str = (char *)malloc(sizeof(char)*10+1);//+1 for '\0'
const char *name = "chase";
snprintf(str, 11, "%-*s", 10, name);//11 is out buffer size
printf(" 1234567890\n");
printf("<%s>\n", str);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.