【发布时间】:2018-03-06 22:51:19
【问题描述】:
这样做之后,
char* example = (char*)malloc(10);
如何将第 5 个字节更改为“a”,以便 printf("%s", example); 给我 " a "?
【问题讨论】:
-
malloc()返回的不是字符串,而是未初始化的缓冲区。在更改“字符串”之前,您必须先用一些字符串对其进行初始化。 -
a[4] = 'a';。但是您也需要添加这些空格,并且不要忘记空终止符 (a[9] = '\0';)。另外,不需要转换malloc()的结果。请改用char *example = malloc(10);。 -
如何将所有字节初始化为空" "?
-
malloc的返回不用强制转换,没必要。请参阅:Do I cast the result of malloc? 和...memset (example, ' ', 9);和example[9] = 0;然后example[4] = 'a'; -
如何将所有字节初始化为空""? —
memset(example, ' ', 9); a[9] = '\0';