Proper way to empty a C-String

前端 未结 6 1868
孤城傲影
孤城傲影 2020-12-04 15:12

I\'ve been working on a project in C that requires me to mess around with strings a lot. Normally, I do program in C++, so this is a bit different than just saying string.e

6条回答
  •  醉梦人生
    2020-12-04 16:14

    Two other ways are strcpy(str, ""); and string[0] = 0

    To really delete the Variable contents (in case you have dirty code which is not working properly with the snippets above :P ) use a loop like in the example below.

    #include 
    
    ...
    
    int i=0;
    for(i=0;i

    In case you want to clear a dynamic allocated array of chars from the beginning, you may either use a combination of malloc() and memset() or - and this is way faster - calloc() which does the same thing as malloc but initializing the whole array with Null.

    At last i want you to have your runtime in mind. All the way more, if you're handling huge arrays (6 digits and above) you should try to set the first value to Null instead of running memset() through the whole String.

    It may look dirtier at first, but is way faster. You just need to pay more attention on your code ;)

    I hope this was useful for anybody ;)

提交回复
热议问题