Home > front end >  Wondering what is wrong with this Declaration as opposed to the commented in code ? - Beginner here
Wondering what is wrong with this Declaration as opposed to the commented in code ? - Beginner here

Time:05-28

// Online C compiler to run C program online

#include <stdio.h>
#include <string.h>

int main()
{
    char *s1 = "Hello";  /* Code doesn't work with this declaration instead works with char s1[] = "Hello"; */

    char *s2 = "world"; 

    strcpy(s1,s2);

    printf("copied is %s into %s",s1,s2);

    return 0;
}

Aren't char *s1 and char s1[] declarations same ?

CodePudding user response:

Aren't char *s1 and char s1[] declarations same ?

The declaration

char *s1 = "Hello";

declares a pointer to a string literal. You may not change a string literal. Any attempt to change a string literal like for example that

strcpy(s1,s2);

results in undefined behavior.

This declaration

char s1[] = "Hello";

declares a character array elements of which are initialized by elements of the string literal. The above declaration is equivalent to

char s1[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

You may change the character array because it is not declared as a constant array.

So this call of strcpy is correct for the array

strcpy(s1,s2);

You could also write for example

char s1[] = "Hello";
char *p = s1;
//...
strcpy(p,s2);

because in this case the pointer p does not point to a string literal. It points to the non-constant character array s1.

And the message in the call of printf

printf("copied is %s into %s",s1,s2);

is wrong. Actually this call

strcpy(s1,s2);

copies characters from s2 into s1.

CodePudding user response:

Aren't char *s1 and char s1[] declarations same ?

No.

char *s1 = "Hello";

declares s1 as a pointer - all it stores is the address of the string literal "Hello":

     ––– 
s1: |   | –––––––––– 
     –––            |
     ...            |
     –––            |
    |'H'| <––––––––– 
     ––– 
    |'e'|
     ––– 
    |'l'|
     ––– 
    |'l'|
     ––– 
    |'o'|
     ––– 
    | 0 |
     ––– 

The behavior on attempting to modify the contents of a string literal (such as with strcpy(s1,s2);) is undefined - your code may crash outright, or it may just fail to update the string, or it may work as expected.

The declaration

char s1[] = "Hello";

allocates an array of char large enough to store the string "Hello" and initializes it with that string:

     –––   
s1: |'H'|
     ––– 
    |'e'|
     ––– 
    |'l'|
     ––– 
    |'l'|
     ––– 
    |'o'|
     ––– 
    | 0 |
     ––– 

This is an actual array that you can modify. It can’t store any strings longer than "Hello", but otherwise you can modify it to your heart’s content.

  • Related