Home > database >  loop with pointer in C
loop with pointer in C

Time:02-22

I was testing around with loops in c, and I came across a post about pointers in loops (for(foo = bar; *foo; foo )).

I tried testing around with this knowledge, and made this:

int main() {
   char a[9] = "test test";
   char *b; 
   for(b = a; *b; b  )
       printf("%c", *b);
   return 0; 
}

I compiled this (gcc test.c), then ran it and got the following output: test test‼ aest test¶ ast test§ at test▬ a test↨ atest↑ aest↓ ast→ ata∟ a aa

I changed char a[9] to char a[10], assuming it had something to do with \0, then got test testest testst testt test testtesteststt.

Why does this happen? I thought that this loop would end after 9 cycles, as there are 9 characters in the string provided.

CodePudding user response:

you problem is here

char a[9] = "test test";

"test test" as a c string takes 10 bytes: 9 for the characters and one for the terminating '\0' character.

Do:

char a[] = "test test";

Ie. let the compiler work out how much memory the string takes.

Why is this an issue?

Because the C runtime detects the end of a string when it sees a '\0' character. You have not got one, so the runtime code runs off the end of the string and keeps going till it hits a '\0'

Also you should do

 printf("%s\n", b); 

so that each loop prints on one line. Do not do printf(<string>) this is asking for trouble

OK, next question is - why doesnt it just print "test test".

 char a[9] = "test test";
 char *b; 
 for(b = a; *b; b  )
     printf("%s\n",b);
 return 0; 

Let's do the first loop. At the print statement:

  • b is a char pointer pointing at the first 'T' in the string
  • printf("%s\n", b) will print the string starting at that point, ie "Test Test"

Second loop, same place

  • b now points at the 'e' character
  • printf("%s\n", b) will print the string starting at that point, ie "est Test"

Third

  • b now points at the 's' character
  • printf("%s\n", b) will print the string starting at that point, ie "st Test"

All clear?

If you want to print the string char by char do

 char a[9] = "test test";
 char *b; 
 for (b = a; *b; b  )
     printf("%c\n", *b);
 return 0; 

That printf says 'print one character, the character pointed at by b.'

  • Related