C语言 为什么会出现此错误:指向整数转换的指针不兼容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14036913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why this error: incompatible pointer to integer conversion?
提问by daNullSet
Please have a look at the code, clang is giving me the error "incompatible pointer to integer conversion", why is it happening?
请看一下代码,clang 给了我错误“整数转换不兼容的指针”,为什么会发生这种情况?
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char* name;
name = malloc (sizeof(char) * 6);
*name = "david";
return 0;
}
回答by K-ballo
Whatever is happening is happening at this line:
这条线上正在发生什么事情:
*name = "david";
The type of *namewould be char, as you are dereferencing the charpointed to by name. The type of "david"is char[6], as it's a string literalof 6 chars (5 + null terminator). An array type decaysinto a pointer and a charis an integral type; your assignment tries to set a pointer to an integer, hence incompatible pointer to integer conversion.
的类型*name将是char,因为您正在取消引用char指向的name。"david"is的类型char[6],因为它是 6 个字符的字符串文字(5 + 空终止符)。数组类型衰减为指针,而 achar是整数类型;您的任务试图设置一个指向整数的指针,因此incompatible pointer to integer conversion.
Even if the left side of the assignment had the right type, you couldn't just copy arrays with the assignment operator. If you want to set nameto "david", then you should be using strcpy( name, "david" ).
即使赋值的左侧具有正确的类型,您也不能仅使用赋值运算符复制数组。如果您想设置name为"david",那么您应该使用strcpy( name, "david" ).
回答by Keerthi Ranganath
In C programming you can never copy/assign the string into a pointer directly like
在 C 编程中,您永远不能像这样直接将字符串复制/分配到指针中
*name = "david";
You can only copy a string using memcpy()(in built function).To fix the issue replace the line*name = "david";with memcpy(name,"david",sizeof("david"));
您可以只复制使用字符串memcpy()(内置功能)。为了解决这个问题替换行*name = "david";用memcpy(name,"david",sizeof("david"));
回答by Travis Griggs
This line:
这一行:
*name = "david";
should read
应该读
name = "david";
*name is synonymous (in this context) with name[0] (i.e. the first character of a string pointed to by the name variable). You want the name variable, not the contents of the pointer, to be assigned to point at the same thing that the string literal "david" is pointing at.
*name 与 name[0] 同义(在此上下文中)(即 name 变量指向的字符串的第一个字符)。您希望将 name 变量而不是指针的内容分配为指向字符串文字“david”所指向的同一事物。
回答by abhay jain
look here name is not a pointer to character
by using the library function malloc you have made it an array of characters
so you cannot simply point it to any address like a pointer
you have to use library function strcpy(p,"david")then only it will give you desired results
看看这里的名字是不是一个指向字符
使用你们倒使它字符数组的库函数malloc
,所以你不能简单地把它指向像是指针的任何地址
,你必须使用库函数的strcpy(P,“大卫”) ,然后只有它会给你想要的结果

