#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;
}
Run Code Online (Sandbox Code Playgroud)
编译警告:
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也是一个指针和你好,发生了什么事?
你做错了:
#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;
}
Run Code Online (Sandbox Code Playgroud)
说明:
strcpy对指针进行操作,其中两者都是要写入和读取的起始位置,因此您必须传递这些,而不是字符.您的读取位置是hello,您的写入位置是str.然后strcpy循环直到找到一个0字符(包括在内)来停止复制,所以你的循环是不必要的.最后一件事是你必须释放分配的内存.也sizeof(char)没有意义:它总是1.