c – warning: assignment makes integer from pointer without a cast

c – warning: assignment makes integer from pointer without a cast

When you write the statement

*src = anotherstring;

the compiler sees the constant string abcdefghijklmnop like an array. Imagine you had written the following code instead:

char otherstring[14] = anotherstring;
*src = otherstring;

Now, its 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 isnt 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 isnt 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.

It appears to me that you are trying to assign a string. Strings in C arent data types like they are in C++ and are instead implemented with char arrays. You cant 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 *.

The expression *src refers to the first character in the string, not the whole string. To reassign src to point to a different string tgt, use src = tgt;.

c – warning: assignment makes integer from pointer without a cast

The warning comes from the fact that youre dereferencing src in the assignment. The expression *src has type char, which is an integral type. The expression anotherstring has type char [14], which in this particular context is implicitly converted to type char *, and its value is the address of the first character in the array. So, you wind up trying to assign a pointer value to an integral type, hence the warning. Drop the * from *src, and it should work as expected:

src = anotherstring;

since the type of src is char *.

Leave a Reply

Your email address will not be published.