Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a string in C to empty string

Tags:

c

string

I want to initialize string in C to empty string. I tried:

string[0] = "";  

but it wrote

"warning: assignment makes integer from pointer without a cast" 

How should I do it then?

like image 387
maayan Avatar asked Nov 10 '10 09:11

maayan


People also ask

How do I completely empty a string in C?

If you want to zero the entire contents of the string, you can do it this way: memset(buffer,0,strlen(buffer));

Can you set a string to null in C?

In practice, NULL is a constant equivalent to 0 , or "\0" . This is why you can set a string to NULL using: char *a_string = '\0'; Download my free C Handbook!


2 Answers

In addition to Will Dean's version, the following are common for whole buffer initialization:

char s[10] = {'\0'}; 

or

char s[10]; memset(s, '\0', sizeof(s)); 

or

char s[10]; strncpy(s, "", sizeof(s)); 
like image 70
Matt Joiner Avatar answered Sep 21 '22 05:09

Matt Joiner


You want to set the first character of the string to zero, like this:

char myString[10]; myString[0] = '\0'; 

(Or myString[0] = 0;)

Or, actually, on initialisation, you can do:

char myString[10] = ""; 

But that's not a general way to set a string to zero length once it's been defined.

like image 39
Will Dean Avatar answered Sep 19 '22 05:09

Will Dean