Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between character array initialized with string literal and one using strcpy

Please help me understand what is the difference using an initialized character array like char line[80]="1:2" ( which doesn't work !! ) and using char line[80] followed by strcpy(line,"1:2").
As per my understanding in first case I have a charachter array, it has been allocated memory, and i am copying a string literal to it. And the same is done in the second case. But obviously I am wrong. So what is wrong with my understanding.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void tokenize(char* line)
{
   char* cmd = strtok(line,":");

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

int main(){
char line[80]; //char line[80]="1:2" won't work 
/*
char *line;
line = malloc(80*sizeof(char));
strcpy(line,"1:2");
*/
strcpy(line,"1:2");
tokenize(line);
return 0;
}
like image 208
mdsingh Avatar asked Dec 17 '25 05:12

mdsingh


1 Answers

You are wrong. The result of these two code snippets

char line[80] = "1:2";

and

char line[80];
strcpy( line, "1:2" );

is the same. That is this statement

char line[80] = "1:2";

does work.:) There is only one difference. When the array is initialized by the string literal all elements of the array that will not have a corresponding initialization character of the string literal will be initialized by '\0' that is they will be zero-initialized. While when function strcpy is used then the elements of the array that were not overwritten by characters of the string literal will have undeterminated values.

The array is initialized by the string literal (except the zero initialization of its "tail") the same way as if there was applied function strcpy.

The exact equivalence of the result exists between these statements

char line[80] = "1:2";

and

char line[80];
strncpy( line, "1:2", sizeof( line ) );

that is when you use function strncpy and specify the size of the target array.

If you mean that you passed on to function tokenize directly the string literal as an argument of the function then the program has undefined behaviour because you may not change string literals.

According to the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

like image 182
Vlad from Moscow Avatar answered Dec 19 '25 21:12

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!