简体   繁体   中英

Issues with char and string assignments on C (integer from pointer without a cast?)

I've made the following declarations on my code:

char bussola, com[1], pen;
int main()
{
   bussola = "oeste", pen = "up";

but for some reason I'm getting this error on the compiler:

 main.c:18:10: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
 
 bussola = "oeste", pen = "up";
           ^             ^

And because of that I keep getting other errors like this one:

main.c:51:17: warning: comparison between pointer and integer
 
 if (bussola == "oeste") 
              ^~

What should I do?

you are assigning a char array (AKA string) to a char variable, they are't compatible data tipes. A char variable can only have single char values (like 'a' , 'F', '2' or ' '). Its important to use single quotes (' ') to interpret the character like a char variable. You can declare a string using char * bussola or char bussola[LENGTH], but you will have to inicialite the array in the declaration:

char bussola[6] = "oeste";

if you want to inicialite it later, you can use strcpy:

char bussola[6];
strncpy(bussola, "oeste", 6);

Be aware that string use doble quotes (" ") instead of single quotes like chars.

char bussola[6], pen[3];

int main() {
   strcpy(bussola, "oeste");
   strcpy(pen, "up");
}
if(!strcmp(bussola,"oeste")

This above is the correct syntax for what you are trying to do.

Considering this code, I would suggest to thorough the strings and character concepts in C and also the string.h header file functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM