我正在编写一个非常简单的程序来使用 malloc 复制字符串。
#include <stdio.h>
#include <stdlib.h>
char * copyStr(char s[])
{
int len = strlen(s); //find length of s
char * copy;
copy = (char *)malloc(len); //dynamically allocate memory
int i;
for(i=0;i<len;i++)
{
copy[i]=s[i]; //copy characters
}
return copy; //return address
}
int main(int argc, char ** argv)
{
char * str;
str = "music is my aeroplane";
char * res;
res = copyStr(str);
printf("The copied string is : %s",res);
getch();
}
期望的输出是:
The copied string is : music is my aeroplane
当前输出为:
The copied string is : music is my aeroplaneOMEeJ8«≤╝
欢迎任何建议。
最佳答案
C 字符串以 null 结尾。在字符串末尾添加一个空字符(即ASCII码为0的字符):
char * copyStr(char s[])
{
size_t len = strlen(s); //find length of s
char * copy;
copy = (char *)malloc(len + 1); //dynamically allocate memory
/* One more char must be allocated for the null char */
size_t i;
for(i=0;i<len;i++)
{
copy[i]=s[i]; //copy characters
}
copy[i] = '\0'; // HERE
return copy; //return address
}
最好使用 size_t
作为长度,因为它是无符号的。
关于c - 在 C 中使用 malloc 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36694345/