strange question

J

Jack

Below is a simple code:

int main(){
char str[] = "How are you.";

int len;
len = strlen(str);
char *p1;

p1 = str + len-1;
printf("str:%s\n", str);
int i;
for( i = len-1; i >= 0; ){
printf("p1:%s\n", p1);
if(*(p1+i) != ' ') { //LINE1
p1--;
i--;
}
else{
i--;
printf("REACH HERE!\n");
}
}

}

The output is:

str:How are you.
p1:.
p1:u.
p1:eek:u.
p1:you.
p1: you.
p1:e you.
p1:re you.
p1:are you.
p1: are you.
p1:w are you.
p1:eek:w are you.
p1:How are you.

Why LINE1 does not work?

Thanks.
 
M

manoj1978

Jack said:
Below is a simple code:

int main(){
char str[] = "How are you.";

int len;
len = strlen(str);
char *p1;

p1 = str + len-1; Now p1 points to str[11]
printf("str:%s\n", str);
int i;
for( i = len-1; i >= 0; ){
printf("p1:%s\n", p1);
if(*(p1+i) != ' ') { //LINE1
First time i is 11 and you are trying to look at str[22] which is not
valid in this program.
 
B

boa

* Jack wrote, On 26.08.2006 07:02:
Below is a simple code:

int main(){
char str[] = "How are you.";

int len;
len = strlen(str);

len = 12
char *p1;

p1 = str + len-1;

Now p1 points to str+11
printf("str:%s\n", str);
int i;
for( i = len-1; i >= 0; ){

i starts out as 11
printf("p1:%s\n", p1);
if(*(p1+i) != ' ') { //LINE1

p1 + i == (str+11+11), way off.
Try: if(str == ' ') or just if(*p1 == ' ')
p1--;
i--;
}
else{
i--;
printf("REACH HERE!\n");
}
}

}


The output is:

str:How are you.
p1:.
p1:u.
p1:eek:u.
p1:you.
p1: you.
p1:e you.
p1:re you.
p1:are you.
p1: are you.
p1:w are you.
p1:eek:w are you.
p1:How are you.

Why LINE1 does not work?

See above.

Boa
 
S

spibou

Jack said:
Below is a simple code:

int main(){
char str[] = "How are you.";

int len;
len = strlen(str);
char *p1;

p1 = str + len-1;
printf("str:%s\n", str);
int i;
for( i = len-1; i >= 0; ){
printf("p1:%s\n", p1);
if(*(p1+i) != ' ') { //LINE1
p1--;
i--;
}
else{
i--;
printf("REACH HERE!\n");
}
}

}

The output is:

str:How are you.
p1:.
p1:u.
p1:eek:u.
p1:you.
p1: you.
p1:e you.
p1:re you.
p1:are you.
p1: are you.
p1:w are you.
p1:eek:w are you.
p1:How are you.

Why LINE1 does not work?

I can only speculate what you intended for
LINE1 to accomplish but what it does do
is undefined behaviour. That's because in
most repetitions of the loop and certainly the
first repetition , p1+i points past the end of str[]
so you are not allowed to dereference it.

Just run in your head the programme or use
a piece of paper or add printf statements which
print the values of variables and it will become
obvious.

Spiros Bousbouras
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top