如何通过在C字符串循环? [英] How to iterate over a string in C?

查看:123
本文介绍了如何通过在C字符串循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我想这样的:

#include <stdio.h>

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

    if (argc != 3) {

        printf("Usage: %s %s sourcecode input", argv[0], argv[1]);
    }
    else {
        char source[] = "This is an example.";
        int i;

        for (i = 0; i < sizeof(source); i++) {

            printf("%c", source[i]);
        }
    }

    getchar();

    return 0;
}

这也并不工作:​​

char *source = "This is an example.";
int i;

for (i = 0; i < strlen(source); i++){

    printf("%c", source[i]);
}

我得到的错误

在将Test.exe 0x5bf714cf(msvcr100d.dll)未处理的异常:0000005:访问冲突在位置0x00000054读书时,

Unhandled exception at 0x5bf714cf (msvcr100d.dll) in Test.exe: 0xC0000005: Access violation while reading at position 0x00000054.

(德国松散翻译)

那么,什么是错我的code?

So what's wrong with my code?

推荐答案

您想要的:

for (i = 0; i < strlen(source); i++){

sizeof的为您提供了指针的大小,而不是字符串。然而,如果你已经宣布的指针数组它会工作:

sizeof gives you the size of the pointer, not the string. However, it would have worked if you had declared the pointer as an array:

char source[] = "This is an example.";

但如果你通过阵列的功能,这也将衰减到一个指针。对于字符串,最好经常使用strlen。并注意别人怎么说,有关改变的printf使用%C。而且,以mmyers评论效率考虑在内,这将是更好的移动呼叫strlen的圈外:

but if you pass the array to function, that too will decay to a pointer. For strings it's best to always use strlen. And note what others have said about changing printf to use %c. And also, taking mmyers comments on efficiency into account, it would be better to move the call to strlen out of the loop:

int len = strlen( source );
for (i = 0; i < len; i++){

或重写循环:

for (i = 0; source[i] != 0; i++){

这篇关于如何通过在C字符串循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆