0

I'm studying C now.

I have tried to learn strcpy function in "string.h". But, I got a problem from that function.

Before writing a problem, I already studied that the difference between char * const and char const * and const char * const.

The problem is I don't know the difference between char * const _ and char _ []. (_ is variable name)

I wrote a code but "example 1" is correct and "example 2" isn't correct to build and execute.

[example 1]

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

int main()    
{    
    char s1[] = "Hello";    
    char s2[] = "";    

    strcpy(s2, s1);

    printf("%s %s\n", s1, s2);

    return 0;
}

*** OUTPUT: Hello Hello

[example 2]

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

int main()
{
    char *const s1 = "Hello";
    char *const s2 = "";

    strcpy(s2, s1);

    printf("%s %s\n", s1, s2);

    return 0;
}

*** OUTPUT: segmentation fault (core dumped)


I knew char * const is equal to array. Isn't it true? And I want to know the problem in this code.

I hope your help. Thank you.

  • Does this answer your question? [Difference between char\* and char\[\]](https://stackoverflow.com/questions/7564033/difference-between-char-and-char) – TruthSeeker Apr 08 '22 at 16:31
  • **Example 1 IS NOT CORRECT**. With `char s2[] = "";` you reserve enough space for `1` byte ... and later you try to write 6 bytes in that space. You got the infamous **Undefined Behaviour** -- code is wrong, but behaves as you expect; leading you to believe it is correct. **Example 1 WRONG!** – pmg Apr 08 '22 at 16:34
  • When a piece of code tries to do read and write operation in a read only location in memory or freed block of memory, it is known as core dump. It is an error indicating memory corruption. So the data is not being stored correctly in s1/s2 – Asn Apr 08 '22 at 16:35
  • Arrays are not pointers ... pointers are not arrays (though they do share access methods). You might like section 6 of the [comp.lang.c FAQ](http://c-faq.com/). – pmg Apr 08 '22 at 16:37

0 Answers0