Lion King Lion King - 3 months ago 8
C++ Question

When we initialize the data type char* and when not?

Firstly, look at the following simple code:

char str[80] = "This is - my text - for test";
const char s[2] = "-";
char *token;
token = strtok(str, s);

while (token != NULL) {
printf(" %s\n", token);
token = strtok(NULL, s);
}


The function
strtok()
returns the data type
char*
and as you seen we created a variable named
token
that variable not initialized.

Now, look at the next code:

char *buff;
int num = 500;
sprintf(buff, "%d", num);


The result of the previous code is an error
uninitialized local variable 'buff'
.

My question is, why in the first code does not occurs any problem, while, in the second code occurred an error ?

Answer

Because in the first snippet you do initialize the variable token, by calling strtok and assigning the result of the call to the variable.

In the second example you leave the variable buff uninitialized.

You can initialize a local variable with an actual initialization at definition. Or by assigning to the variable elsewhere. The important thing is that you do this initialization or assignment before you use the variable in any other way.