首页 > 解决方案 > String traversal using pointers

问题描述

I am trying to print every fourth character of a string using pointers.

I was able to achieve it using the following code:

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

int main(int argc, char const *argv[]){

char* string = "WhatTheeHell";
char* p = string;

while(*p != '\0'){
    printf("%c\n", *p);
    p += 4;
}

return 0;

}

This correctly gives the output to me as:

W

T

H

Now, I tried another way to do it, which according to my knowledge of pointer arithmetic, should have worked, since the size of int on my machine is 4 bytes.

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

int main(int argc, char const *argv[]){


    char* string = "WhatTheeHell";
    int* p = (int*)string;

    while(*p != '\0'){
        printf("%c\n", *p);
        p += 1;
    }

    return 0;

}

When I print the output for this, it gives me WTH followed by four newlines.

My question, why are the four newlines being printed? Shouldn't it be that after the H is printed, the *p gives a NULL character present at the end of the string literal and the loop gets terminated?

标签: cpointersc-stringspointer-arithmetic

解决方案


对于初学者来说,第一个程序是无效的。如果字符串的字符数不能被您整除,4则将具有未定义的行为,因为指针可以使用指针算术指向字符串之外

p += 4;

一个有效的方法可以如下所示,如演示程序中所示

#include <stdio.h>

int main( void )
{
    const char *s = "WhatTheeHell";
    const size_t STEP = 4;

    if ( *s )
    {
        const char *p = s;
        do
        {
            printf( "%c\n", *p );
            for ( size_t i = 0; i < STEP && *p; ++i, ++p );
        } while ( *p );            
    }
}

它的输出是

W
T
H

第二个你的程序也是无效的。对于初学者来说,没有必要将字符串文字对齐sizeof( int )(而且通常sizeof( int )可以大于或小于 4)。所以程序已经有未定义的行为。

在这种情况下

*p != '\0'

sizeof( int )字节(不是单个字节)与整数常量进行比较'\0'。所以比较总是true当指针指向字符串内部时(如果没有零字节,甚至超出字符串)。

顺便还要注意,在 Csizeof( '\0' )中等于sizeof( int )


推荐阅读