Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

c - How to use default values in a char array?

I have the easiest question possible: how to initialise a value in C? My variable is of the type char[20] and it is declared somewhere outside of my unit. It is impossible to change the type.

Now I would like to give it a default value, let's say all empty characters (or spaces, whatever), but this is not working at all. I have already tried :

Method 1.

host = "";

=> cannot convert from 'const char [1]' to 'char [20]'

Method 2.

host = "                   ";

=> cannot convert from 'const char [20]' to 'char [20]

Method 3.

host = '                   ';

=> cannot convert from 'int' to 'char [20]

Method 4.

host = {"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", };

=> syntax error : '{'

...

I am getting desperate here: how and why have the inventors of C made it so difficult to simply declare a value to a variable :-( ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
memset(&host, 0, sizeof(host));

will fill it with zeroes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...