Mustafa
Mustafa

Reputation: 177

using pointers for string in c

So I wrote this code

char *word = "Metal Gear";
int counter = 0;
printf("word = ");

for(;;)
{
     printf("%c", *word);
     *(word++);
     counter++;
     if(*word == '\0')
        break;
}

The variable counter to count the length of my word string.
How come this code does not print the null character?
I know that I told it to break once it encounters a null character, but my print statement is before the if clause, so shouldn't it print it then break out of the loop.
How come there's no difference if the if clause is at the very beginning of the for loop ?!

update: while I'm at it, does c allow variable length for arrays or not?
I'm confused by this because I read that it allows it and that it doesn't.
My assumption that c99 allows it but many articles and blogs haven't been updated since the release of c99 standard. Am I correct?

Upvotes: 0

Views: 70

Answers (3)

pmg
pmg

Reputation: 108978

while I'm at it, does c allow variable length for arrays or not? I'm confused by this because I read that it allows it and that it doesn't. My assumption that c99 allows it but many articles and blogs haven't been updated since the release of c99 standard. Am I correct?

VLAs were introduced with C99. Sites that say C allows them are correct; sites that say C does not allow VLAs are out of date.

However, there are still C compilers/implementations in use that target C89 (C90, C94) (eg: gcc -std=c89 -pedantic ...). For these compilers, VLAs are not an option.

Anyway, except for very small arrays, you should not use VLAs in your code :)
Mainly because VLAs have no error checking.

Upvotes: 0

Kaushik Koneru
Kaushik Koneru

Reputation: 99

First thing: printf expects a valid (i.e. non-NULL) pointer for its %c argument so passing it a NULL is officially undefined and is smart

Second : According to logic You break from for loop before printing. If you want to check try following.

 #include <stdio.h>
 #include <string.h>

 int main()
  {
       char *word = "Metal Gear";
       int counter = 0;
       printf("word = ");

    for(;;)
     {
      printf("%c ", *word);
      if(*word == '\0'){
          printf("%d", counter);
          break;
       }
        *(word++);
        counter++;
     }
      return 0;
   }

As in printf, i have given space extra it will print as "word = M e t a l G e a r 10" with 2 space gap between 'r' & '10'

Upvotes: 0

Lundin
Lundin

Reputation: 213563

How come this code does not print the null character?

Because you break the loop before it is printed. Also, a null character likely does not have any visual representation, so even if you print it, you would probably see nothing.

my print statement is before the if clause, so shouldn't it print it then break out of the loop.

You increase the pointer by 1 after printing, so when determining when to break, you always check the next character after the one you just printed.

Upvotes: 1

Related Questions