Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning: assignment makes integer from pointer without a cast

Tags:

c

casting

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.

like image 754
lcutler Avatar asked Feb 25 '11 20:02

lcutler


People also ask

How do you solve warning assignment makes integer from pointer without a cast?

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 * .

What is Wint conversion error?

It means exactly what it says: You are trying to assign an address ( pointer value ) to an integer variable. While this is tecnhically allowed, doing so without explicitly converting the pointer to an int is a sign this is probably not what you were intending , hence the warning. (


1 Answers

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, 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.

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 *.

like image 188
bta Avatar answered Oct 08 '22 21:10

bta