#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 回答
你做错了:
说明:
strcpy
对指针进行操作,两者都是要写入和读取的起始位置,因此您必须传递这些,而不是字符 . 您的阅读位置是hello
,您的写入位置是str
. 然后strcpy
循环,直到它找到0
字符(包括在内)来停止复制,因此你的循环是不必要的 . 最后一件事是你必须释放分配的内存 . 此外sizeof(char)
不会't make sense: it'总是1 .这里的问题是你试图使用C字符串作为字符数组,这当然是允许的,但它与使用它们作为指向空终止字符串的指针的行为不同 . 执行
hello[0]
会计算字符串的第一个字符,这通常是一个8位整数 .char
是一个值,它不对应于内存地址 . 你想要的正确陈述是作为参考,如果你想从字符串中的某个点开始获取字符串,你会这样做
对指针执行加法求值为指针,该指针是内存中前进的n个地址 .
strcpy
的定义需要两个char
指针而不是str[]
,hello[]
数组 .