How to empty a char array?

后端 未结 13 1772
抹茶落季
抹茶落季 2021-01-29 19:33

Have an array of chars like char members[255]. How can I empty it completely without using a loop?

char members[255];

By \"empty\" I mean that

相关标签:
13条回答
  • 2021-01-29 19:44

    char members[255] = {0};

    0 讨论(0)
  • 2021-01-29 19:45

    Use bzero(array name, no.of bytes to be cleared);

    0 讨论(0)
  • 2021-01-29 19:49

    Don't bother trying to zero-out your char array if you are dealing with strings. Below is a simple way to work with the char strings.

    Copy (assign new string):

    strcpy(members, "hello");
    

    Concatenate (add the string):

    strcat(members, " world");
    

    Empty string:

    members[0] = 0;
    

    Simple like that.

    0 讨论(0)
  • 2021-01-29 19:54

    You can use the following instruction:

    strcpy_s(members, "");
    
    0 讨论(0)
  • 2021-01-29 19:57

    Disclaimer: I don't usually program in C so there may be any syntax gotcha in my examples, but I hope the ideas I try to express are clear.

    If "emptying" means "containing an empty string", you can just assign the first array item to zero, which will effectively make the array to contain an empry string:

    members[0] = 0;
    

    If "emptying" means "freeing the memory it is using", you should not use a fixed char array in the first place. Rather, you should define a pointer to char, and then do malloc / free (or string assignment) as appropriate.

    An example using only static strings:

    char* emptyString="";
    char* members;
    
    //Set string value
    members = "old value";
    
    //Empty string value
    member = emptyString
    
    //Will return just "new"
    strcat(members,"new");
    
    0 讨论(0)
  • 2021-01-29 19:58

    Depends on what you mean by 'empty':

    members[0] = '\0';
    
    0 讨论(0)
提交回复
热议问题