How to empty a char array?

后端 未结 13 1773
抹茶落季
抹茶落季 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:59

    By "empty an array" if you mean reset to 0, then you can use bzero.

    #include <strings.h>  
    void bzero(void *s, size_t n);  
    

    If you want to fill the array with some other default character then you may use memset function.

    #include <string.h>  
    void *memset(void *s, int c, size_t n);  
    
    0 讨论(0)
  • 2021-01-29 20:00

    EDIT: Given the most recent edit to the question, this will no longer work as there is no null termination - if you tried to print the array, you would get your characters followed by a number of non-human-readable characters. However, I'm leaving this answer here as community wiki for posterity.

    char members[255] = { 0 };
    

    That should work. According to the C Programming Language:

    If the array has fixed size, the number of initializers may not exceed the number of members of the array; if there are fewer, the remaining members are initialized with 0.

    This means that every element of the array will have a value of 0. I'm not sure if that is what you would consider "empty" or not, since 0 is a valid value for a char.

    0 讨论(0)
  • 2021-01-29 20:00

    I'd go with

    members_in_use = 0;
    
    0 讨论(0)
  • 2021-01-29 20:04

    You cannot empty an array as such, it always contains the same amount of data.

    In a bigger context the data in the array may represent an empty list of items, but that has to be defined in addition to the array. The most common ways to do this is to keep a count of valid items (see the answer by pmg) or for strings to terminate them with a zero character (the answer by Felix). There are also more complicated ways, for example a ring buffer uses two indices for the positions where data is added and removed.

    0 讨论(0)
  • 2021-01-29 20:05

    simpler is better - make sense?

    in this case just members[0] = 0 works. don't make a simple question so complicated.

    0 讨论(0)
  • 2021-01-29 20:06
    members[0] = 0;
    

    is enough, given your requirements.

    Notice however this is not "emptying" the buffer. The memory is still allocated, valid character values may still exist in it, and so forth..

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