c - 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?
解决方案
对于初学者来说,第一个程序是无效的。如果字符串的字符数不能被您整除,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 )
。
推荐阅读
- javascript - 使用 Jquery 限制文本字段
- json - POST 返回 404,而 GET 在 Ajax 调用 SpringMVC 控制器时工作正常
- c# - 抽象类和具体类 - getter 和 setter
- character-encoding - ZPL 打印 € 和带有锐角的字符
- java - 本地日期时间 JPA - Java 8
- java - 返回上一个开关盒
- r - 如何通过字符串列半连接两个数据帧,其中一个以冒号分隔
- c++ - 选择功能将 Enter 键(来自用户输入)识别为客户端请求
- powerbi - PowerBI:获取每个位置和日期的区域最大值
- python - ValueError:没有足够的值来解包(预期为 3,得到 1)以打开图像