vim said:
Hi everyone
I have a doubt in this program
I have a doubt as well, since it doesn't compile at all:
gcc.exe -c main.c -pedantic -W -Wall -Wextra -ansi
In file included from main.c:1:
main.c:3: warning: return type defaults to `int'
main.c: In function `main':
main.c:5: error: `hello' undeclared (first use in this function)
main.c:5: error: (Each undeclared identifier is reported only once
main.c:5: error: for each function it appears in.)
main.c:4: warning: unused variable `str1'
make.exe: *** [main.o] Error 1
Execution terminated
#include<stdio.h>
main()
{
char str1[]="hello";
char *p=hello;
p="bye";
}
According to this program p is pointer to the string hello.When we made
to point to bye.Only 3 letters should erase.But it is giving bye .
Why?
[Provided you fix it, and add a `printf()` so it does output
something.]
Because what you assign to `p` is not a string "bye" but a pointer to a
constant string literal "bye". In case of `str1`, what you've written
is just shorthand for array initialisation:
char str1[] = {'h','e','l','l','o','\0'};
In the second line you probably meant:
char *p = "hello";
which again assigns to `p` a pointer to a constant string literal
"hello".
Constant string literals are held somewhere in memory (you don't know,
and shoudln't care), and you're not allowed to modify them, i.e.:
*p = 'Z';
is illegal.