cstrcpy

What is the difference between char *p and char p[] in strcpy


What is the difference between char *p and char p[] in two below code:

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

void main()
{
    char source[]="stackflow";
    char target[0];
    strcpy(target,source);
    printf("%s", target);
}
#include<stdio.h>
#include<string.h>

void main()
{
    char source[]="stackflow";
    char *target;
    strcpy(target,source);
    printf("%s", target);
}

Why is the former working while the letter not?


Solution

  • In this code, it does not matter as both codes invoke undefined behaviour (UB).

    You need to define a large enough array or allocate enough memory to accommodate the source string.

    When you pass an array or pointer to the strcpy they will behave the same because references are passed by value and arrays decay to pointers in expressions.

    Why is the former working while the letter not?

    Because it is the nature of undefined behaviour. C standard does not say what will happen if you execute the code invoking it. It may fail or not, format your disk, send you card details to hacker or maybe something else