简体   繁体   中英

How to assign char to char* in C?

This code doesn't work.

char* randomWordHidden[length];
char try;

printf("Enter a letter: ");
scanf(" %c", &try);

//here there is a loop    
  randomWordHidden[i] = try; //assign position of randomWordHidden with try value

it gives error: [Warning] assignment makes pointer from integer without a cast

But I do this and it works:

randomWordHidden[i] = "H";

How can i assign to a position of randomWordHidden the value of try var?

Well;

you have made a list (of length length ) of pointers to characters. I guess what you want is:

char randomWordHidden[length];

that should be length characters.

Your randomWordHidden is not an array of char , but an array of char* , so effectively an array of strings. That's why assigning a char gives you a warning, because you cannot do char* = char . But the assignment of "H" , works, because it is NOT a char - it is a string ( const char* ), which consists of letter 'H' followed by terminating character '\\0' . This is char - 'H' , this is string ( char array) - "H" .

You most likely need to change the declaration of the randomWordHidden array to char instead of char* .

I believe arrays are already pointers, no need for that declaration.

char randomWordHidden[length];

Give that a try?

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