Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to initialize a NULL-terminated array of strings in C

Tags:

arrays

c

string

Is this code correct?

char *argv[] = { "foo", "bar", NULL };
like image 263
jjardon Avatar asked May 01 '10 17:05

jjardon


People also ask

How do you null terminate a string in C?

The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0'). When we write some string using double quotes (“…”), then it is converted into null terminated strings by the compiler.

How do you initialize a string array in C?

A more convenient way to initialize a C string is to initialize it through character array: char char_array[] = "Look Here"; This is same as initializing it as follows: char char_array[] = { 'L', 'o', 'o', 'k', ' ', 'H', 'e', 'r', 'e', '\0' };

Is an array null-terminated in C?

So a string in C is a type of an array, namely a char array which is null-terminated array. The null character marks the end of the array to make it easy to know when the string ends (and thereby avoid moving off the end of an array and possibly causing a memory violation).

Why does C use null-terminated strings?

Because in C strings are just a sequence of characters accessed viua a pointer to the first character. There is no space in a pointer to store the length so you need some indication of where the end of the string is. In C it was decided that this would be indicated by a null character.


2 Answers

It's syntactically correct, and it does create a NULL-terminated array of strings.

argv is passed to main as char*[] (or equivalently, char**), but it's "more correct" to treat string literals as a const char* rather than a char*. So with this particular example you'd want const char *argv[] = {"foo", "bar", NULL };

Maybe you aren't really going to initialise it with "foo", but actually with a modifiable string that you will want to modify via argv. In that case char*[] is right. This is the kind of thing Charles probably means by saying that whether code is "correct" depends on what you do with it.

like image 51
Steve Jessop Avatar answered Oct 01 '22 10:10

Steve Jessop


There's nothing obviously wrong the declaration or the initialization but whether it is "correct" depends on what the rest of the code actually does with argv.

like image 24
CB Bailey Avatar answered Oct 01 '22 10:10

CB Bailey