Initialize a string in C to empty string

前端 未结 9 1474
甜味超标
甜味超标 2020-12-24 15:06

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

string[0] = \"\"; 

but it wrote

\"warning: assignment makes inte         


        
相关标签:
9条回答
  • 2020-12-24 15:19

    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.

    0 讨论(0)
  • 2020-12-24 15:24

    Assigning string literals to char array is allowed only during declaration:

    char string[] = "";
    

    This declares string as a char array of size 1 and initializes it with \0.

    Try this too:

    char str1[] = ""; 
    char str2[5] = ""; 
    printf("%d, %d\n", sizeof(str1), sizeof(str2)); //prints 1, 5
    
    0 讨论(0)
  • 2020-12-24 15:26

    calloc allocates the requested memory and returns a pointer to it. It also sets allocated memory to zero.

    In case you are planning to use your string as empty string all the time:

    char *string = NULL;
    string = (char*)calloc(1, sizeof(char));
    

    In case you are planning to store some value in your string later:

    char *string = NULL;
    int numberOfChars = 50; // you can use as many as you need
    string = (char*)calloc(numberOfChars + 1, sizeof(char));
    
    0 讨论(0)
  • To achieve this you can use:

    strcpy(string, "");
    
    0 讨论(0)
  • 2020-12-24 15:28

    It's a bit late but I think your issue may be that you've created a zero-length array, rather than an array of length 1.

    A string is a series of characters followed by a string terminator ('\0'). An empty string ("") consists of no characters followed by a single string terminator character - i.e. one character in total.

    So I would try the following:

    string[1] = ""

    Note that this behaviour is not the emulated by strlen, which does not count the terminator as part of the string length.

    0 讨论(0)
  • 2020-12-24 15:30

    Assuming your array called 'string' already exists, try

    string[0] = '\0';
    

    \0 is the explicit NUL terminator, required to mark the end of string.

    0 讨论(0)
提交回复
热议问题