首页 文章

为什么我不能strcpy?

提问于
浏览
5
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main() {
   const char* hello = "Hello, World!";
   char *str = malloc(14 * sizeof(char));

   for (int i = 0; i < 14; i++) {
      strcpy(str[i],hello[i]);
   }
   str[14]='\0';

   printf("%s\n", str);

   return 0;
}

编译警告:

warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast [-Wint-conversion]   
note: expected 'char *' but argument is of type 'char'   
warning: passing argument 2 of 'strcpy' makes pointer from integer without a cast [-Wint-conversion]

str也是一个指针和你好,发生了什么事?

3 回答

  • 0

    你做错了:

    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    
    int main() {
       const char* hello = "Hello, World!";
       char *str = malloc(strlen(hello)+1);
    
       strcpy(str,hello);
       printf("%s\n", str);
       free(str);
       return 0;
    }
    

    说明: strcpy 对指针进行操作,两者都是要写入和读取的起始位置,因此您必须传递这些,而不是字符 . 您的阅读位置是 hello ,您的写入位置是 str . 然后 strcpy 循环,直到它找到 0 字符(包括在内)来停止复制,因此你的循环是不必要的 . 最后一件事是你必须释放分配的内存 . 此外 sizeof(char) 不会't make sense: it'总是1 .

  • 5

    这里的问题是你试图使用C字符串作为字符数组,这当然是允许的,但它与使用它们作为指向空终止字符串的指针的行为不同 . 执行 hello[0] 会计算字符串的第一个字符,这通常是一个8位整数 . char 是一个值,它不对应于内存地址 . 你想要的正确陈述是

    strcpy(str, hello);
    

    作为参考,如果你想从字符串中的某个点开始获取字符串,你会这样做

    strcpy(str, hello + 1);
    

    对指针执行加法求值为指针,该指针是内存中前进的n个地址 .

  • 1

    strcpy 的定义需要两个 char 指针而不是 str[]hello[] 数组 .

    char *strcpy(char *destination, const char *source)
    

相关问题