Initialize a string in C to empty string

前端 未结 9 1509
甜味超标
甜味超标 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:39
    string[0] = "";
    
    "warning: assignment makes integer from pointer without a cast

    Ok, let's dive into the expression ...

    0 an int: represents the number of chars (assuming string is (or decayed into) a char*) to advance from the beginning of the object string

    string[0]: the char object located at the beginning of the object string

    "": string literal: an object of type char[1]

    =: assignment operator: tries to assign a value of type char[1] to an object of type char. char[1] (decayed to char*) and char are not assignment compatible, but the compiler trusts you (the programmer) and goes ahead with the assignment anyway by casting the type char* (what char[1] decayed to) to an int --- and you get the warning as a bonus. You have a really nice compiler :-)

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

    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));
    
    0 讨论(0)
  • 2020-12-24 15:41

    I think Amarghosh answered correctly. If you want to Initialize an empty string(without knowing the size) the best way is:

    //this will create an empty string without no memory allocation. 
    char str[]="";// it is look like {0}
    

    But if you want initialize a string with a fixed memory allocation you can do:

    // this is better if you know your string size.    
    char str[5]=""; // it is look like {0, 0, 0, 0, 0} 
    
    0 讨论(0)
提交回复
热议问题