为什么我不能做 strcpy?

Why can't I do strcpy?

#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]='[=10=]';

   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 也是一个指针,你好,这是怎么回事?

strcpy 的定义采用两个 char 指针而不是 str[]hello[] 数组。

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

这里的问题是您试图将 C 字符串用作字符数组,这当然是允许的,但与将它们用作 指针 到 [=20= 是不同的行为]null-terminated 字符串。执行 hello[0] 计算出字符串的第一个字符,它通常只是一个 8 位整数。 A char 是一个值,它不对应一个内存地址。 你想要的正确说法是

strcpy(str, hello);

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

strcpy(str, hello + 1);

对指针执行加法计算得到的指针在内存中向前移动了 n 个地址。

你做错了:

#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) 也没有意义:它总是 1.