简体   繁体   中英

What happens when a string contains only '\0'? C

In my program I'm reading words from a .txt file and I will be inserting them into both a linked list and a hash table.

If two '\\n' characters are read in a row after a word then the second word the program will read will be '\\n', however I then overwrite it with '\\0', so essentially the string contains only '\\0'.

Is it worth me putting an if statement so the next part of my program only executes if the word is a real word (ie word[0] != '\\n')? Would the string '\\0' use up space in the hash table/linked list?

In C a character array with first element being \\0 is an empty string , ie of length zero. There's not much sense in keeping empty strings in containers, if that's what you are asking.

It depends if you consider an empty string a valid entry. You seem to be storing words so I would guess that an empty string is of no interest, but that is application specific.

For example, an environment variable can be present ( getenv returns a valid pointer) but the value can be "unset": an empty string. In that case the fact that the value is an empty string might be significant.

So, if an empty string is not significant is it worth adding an if statement to ignore it? Generally that would be a "yes", since the overhead of storing and maintaining the empty string could be significantly more than one if statement per entry. But of course that is only a guess, I don't know what your overheads are, how many times that if would get executed, and how many empty string entries you would be saving. You might not know that either, so my fallback position would be only to store data that is significant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM