Why this program can compiling and run but the result is out of my expectation?`
#include<stdio.h>
int main(void)
{
char *message="hello";
for(int i=0;*message!='\0';i )
{
printf("%c",message[i]);
}
return 0;
}
But this one can meet my expection.(print "hello" rightly)
int main(void)
{
char *message="hello";
for(int i=0;*message!='\0';i )
{
printf("%c",*message );
}
return 0;
}
In the C language,arr[i] is equal to *arr.But in the cases I show above,the result is totally different,when I run them in the devc .Due to my limited knowledge ,I can't understand this.
Because I'm a student who is going to be a freshman after this summer vacation and only have some konwledge about C language,please answer my question in a more acceptable way. Thanks in advance!
***sorry ,the problem is caused because of my carelessness.I have learned my mistake.
CodePudding user response:
In the C language, arr[i] is equal to *arr....
No, *arr
is equal to arr[0]
.
In your first example, you type message
which make et points on the next character.
So, the first code can be corrected that way:
for(int i=0; message[i]!='\0'; i )
{
printf("%c",message[i]);
}
And the second can be simplified: (you don't need i
):
for( ;*message!='\0'; )
{
printf("%c",*message );
}
CodePudding user response:
In the first code, the pointer message
isn't changed and what the pointer message
points at is also not changed, so the condition *message!='\0'
is always true (doing 'h'!='\0'
).
Therefore, i
will continuously be incremented and become so large that message[i]
goes out of a region where access is allowed.
The condition should be message[i]!='\0'
to avoid this error.
If you want to stick to use *
operator for some reason, it should be *(message i)!='\0'
.
CodePudding user response:
I rewrite the program with a slightly different appearance
#include<stdio.h>
int main(void)
{
char *message="hello";
for(int i=0; 'h'!='\0';i ) // notice the change here
{
printf("%c",message[i]);
}
return 0;
}
You see the problem now?
*message
is always h
, it's not changing with the loop iteration. The comparison is meaningless here, it does not terminate the loop as expected.
You need to ensure that you change the pointer to the next address every time you iterate, to ensure you are checking the value of the next element.
You can make use of the index value, like
for(int i=0; * (message i) !='\0';i )