for sizeof(x) VS while ([x] != '\0') in C

Viewed 91

I'm just wondering if there was a difference between using

for(i = 0; i < sizeof(argv[1]) / sizeof(argv[1][0]); i++) {

and

while (argv[1][i] != '\0')

I'm just curious and I can't find anything about it.

(The objective is to putchar every character of the char*)

2 Answers

There is an essential difference in the two conditions.

The expression argv[1] is a pointer having the type char * and usually occupies either 4 or 8 bytes depending on the used system that is equal to the value of the expression sizeof(argv[1]) / sizeof(argv[1][0]) or equivalently of the expression sizeof( argv[1] ) because sizeof( argv[1][0] ) is the same as sizeof( char ) and the last is always equal to 1

On the other hand the pointer can point to a string with much more (or less) characters than 4 or 8.

But even if you will apply the sizeof operator for a character array (instead of a pointer) declared for example like

char s[] = "Hello";

then even in this case the conditions of the loops will be different. That is this for loop

for(i = 0; i < sizeof( s ) / sizeof( s[0]); i++) {

is equivalent to

for(i = 0; i < 6; i++) {

because the terminating zero is also included in the array. That is the body of the loop will get the control also for the character '\0'.

While this loop

while ( s[i] != '\0')

stops its iterations when the character '\0' is encountered.

Here is a demonstrative program that shows the difference. The program outputs ASCII codes of symbols.

#include <stdio.h>

int main(void) 
{
    char s[] = "Hello";
    
    for ( size_t i = 0; i < sizeof( s ) / sizeof( s[0]); i++ )
    {
        printf( "%d ", s[i] );
    }
    
    putchar( '\n' );
    
    size_t i = 0;
    
    while ( s[i] != '\0' )
    {
        printf( "%d ", s[i] );
        ++i;
    }
    
    putchar( '\n' );
    
    
    return 0;
}

The program output is

72 101 108 108 111 0 
72 101 108 108 111 

They are not the same thing (although they're close).

The first one

for(i = 0; i < sizeof(argv[1]) / sizeof(argv[1][0]); i++) {

means:

  1. Set i to 0

  2. sizeof(argv[1]) / sizeof(argv[1][0]) means strlen(argv[1]), so it means

while i is less than the length of argv[1]

which is basically the same thing as

int i = 0;
while(argv[1][i++] != '\0')

There are 2 differences:

  1. In the second one, i is never set to 0

  2. In the second one, i is never incremented (although in the loop itself it may be incremented)

Related