c - 在 C 中使用 malloc 的字符串

标签 c

我正在编写一个非常简单的程序来使用 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/

相关文章:

python - 使用 C API 创建 Python 包

c - 在c中使用时系统命令的返回值是什么

c - 仅使用一个整数和 putchar 打印出 2 位数字

c - 垃圾值的来源是什么?

c - 从 Linux C 向许多 Android 手机发送 UDP 消息

c - 关于Getcontext函数的问题

c - 试图理解 : invalid operands to to binary expression, C

c - 与进程树中的兄弟共享PID

c - 如何避免过早杀死子进程?

c# - 在 C# 中计算 CRC16