简体   繁体   English

如何在C中将char分配给char *?

[英]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 它给出错误:[Warning]分配使指针从整数开始而无需强制转换

But I do this and it works: 但是我这样做,它的工作原理是:

randomWordHidden[i] = "H";

How can i assign to a position of randomWordHidden the value of try var? 如何将try var的值分配给randomWordHidden的位置?

Well; 好;

you have made a list (of length length ) of pointers to characters. 您已经列出了一个字符指针列表(长度为length )。 I guess what you want is: 我想你想要的是:

char randomWordHidden[length];

that should be length characters. 应该是length字符。

Your randomWordHidden is not an array of char , but an array of char* , so effectively an array of strings. 您的randomWordHidden不是char数组,而是char*数组,因此实际上是字符串数组。 That's why assigning a char gives you a warning, because you cannot do char* = char . 这就是为什么分配一个char给您一个警告的原因,因为您不能做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' . 但是"H"的分配有效,因为它不是一个char -它是一个字符串( const char* ),它由字母'H'和结尾的字符'\\0' This is char - 'H' , this is string ( char array) - "H" . 这是char - 'H' ,这是字符串( char数组)- "H"

You most likely need to change the declaration of the randomWordHidden array to char instead of char* . 您很可能需要将randomWordHidden数组的声明更改为char而不是char*

I believe arrays are already pointers, no need for that declaration. 我相信数组已经是指针,不需要该声明。

char randomWordHidden[length]; char randomWordHidden [length];

Give that a try? 试试看吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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