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?
In this code, it does not matter as both codes invoke undefined behaviour (UB).
target
is an array of length zero and you write outside the array bounds (it has zero length)target
is an uninitialized pointer and you dereference it invoking UB.You need to define a large enough array or allocate enough memory to accommodate the source
string.
char target[strlen(source) + 1];
char *target = malloc(strlen(source) + 1);
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