The following program runs well
#include<stdio.h>
#include <string.h>
int main() {
char output[2][3];
strcpy(output[0],"hello");
printf("output[0] = %s\n",output[0]);
printf("output[1] = %s\n",output[1]);
}
OUTPUT
output[0] = hello
output[1] = lo
It can be observed that if string size is more data overlaps next element
if I modify the above program as given below, it shows warning and error
#include<stdio.h>
#include <string.h>
int main() {
char output[2][3];
strcpy(output[0],"hello world");
printf("output[0] = %s\n",output[0]);
printf("output[1] = %s\n",output[1]);
}
OUTPUT **
writing 12 bytes into a region of size 6 overflows the destination
**
but if I use char pointer array, it works for any length of the string as below
#include<stdio.h>
#include <string.h>
int main() {
char *output[2] ;
output[0]="Hello World" ;
output[1]="Country" ;
printf("output[0] = %s\n",output[0]);
printf("output[1] = %s\n",output[1]);
printf("address of output[0] = %p\n",&output[0]);
printf("address of output[1] = %p\n",&output[1]);
}
OUTPUT
output[0] = Hello World
output[1] = Country
address of output[0] = 0x7ffe89dc4210
address of output[1] = 0x7ffe89dc4218
As can be observed size of output0 is 8, I have tried with char pointer array of size 10 also, irrespective of the number of character entered to each element of the array, the difference between the address of elements remains 8 It's also not overlapping the next element of the array also as observed in the first case.
- How is this happening?
- Where is memory coming from, for long strings in case of char pointer array?
- Which is better to use
char output[][]
orchar *output[]
?
Adding one more example
#include<stdio.h>
#include <string.h>
int main() {
char *output[2] ;
output[0]="Hello World" ;
output[1]="Country" ;
printf("output[0] = %s\n",output[0]);
printf("output[1] = %s\n",output[1]);
printf("address of output[0] = %p\n",&output[0]);
printf("address of output[1] = %p\n",&output[1]);
output[0]="Text Parsing in c" ;
output[1]="text" ;
printf("output[0] = %s\n",output[0]);
printf("output[1] = %s\n",output[1]);
printf("address of output[0] = %p\n",&output[0]);
printf("address of output[1] = %p\n",&output[1]);
}
OUTPUT
output[0] = Hello World
output[1] = Country
address of output[0] = 0x7fff5cf668e0
address of output[1] = 0x7fff5cf668e8
output[0] = Text Parsing in c
output[1] = text
address of output[0] = 0x7fff5cf668e0
address of output[1] = 0x7fff5cf668e8