Initialize a string in C to empty string

前端 未结 9 1507
甜味超标
甜味超标 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: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));
    

提交回复
热议问题