警告:赋值从指针生成整数而不进行强制转换 [英] warning: assignment makes integer from pointer without a cast
问题描述
当我将 char *
声明为固定字符串并重用指针指向另一个字符串时
When I declare a char *
to a fixed string and reuse the pointer to point to another string
/* initial declaration */
char *src = "abcdefghijklmnop";
.....
/* I get the "warning: assignment makes integer from pointer without a cast" */
*src ="anotherstring";
我尝试重铸指针,但没有成功.
I tried to recast the pointer but no success.
推荐答案
写语句时
*src = "anotherstring";
编译器将常量字符串 "abcdefghijklmnop"
视为数组.假设您编写了以下代码:
the compiler sees the constant string "abcdefghijklmnop"
like an array. Imagine you had written the following code instead:
char otherstring[14] = "anotherstring";
...
*src = otherstring;
现在,发生的事情更清楚了.左边的 *src
指的是一个 char
(因为 src
是指向 char 的指针类型
code>) 而右侧的 otherstring
指的是一个指针.
Now, it's a bit clearer what is going on. The left-hand side, *src
, refers to a char
(since src
is of type pointer-to-char
) whereas the right-hand side, otherstring
, refers to a pointer.
这并不是严格禁止的,因为您可能想要存储指针指向的地址.但是,在这种情况下通常使用显式强制转换(这种情况不太常见).编译器发出危险信号,因为您的代码可能没有按照您的预期运行.
This isn't strictly forbidden because you may want to store the address that a pointer points to. However, an explicit cast is normally used in that case (which isn't too common of a case). The compiler is throwing up a red flag because your code is likely not doing what you think it is.
在我看来,您正在尝试分配一个字符串.C 中的字符串不是 C++ 中的数据类型,而是使用 char
数组实现的.您不能像尝试那样直接为字符串赋值.相反,您需要使用 strncpy
之类的函数和 <string.h>
中的朋友,并使用 char
数组而不是 char
指针.如果您只想让指针指向不同的静态字符串,请删除 *
.
It appears to me that you are trying to assign a string. Strings in C aren't data types like they are in C++ and are instead implemented with char
arrays. You can't directly assign values to a string like you are trying to do. Instead, you need to use functions like strncpy
and friends from <string.h>
and use char
arrays instead of char
pointers. If you merely want the pointer to point to a different static string, then drop the *
.
这篇关于警告:赋值从指针生成整数而不进行强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!