C数组中的增量指针 [英] Incrementing pointers in C arrays

查看:81
本文介绍了C数组中的增量指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图了解以下程序.具体来说,cur_name的定义和printf语句中cur_age的指针的增量.

I'm trying to understand the below program. Specifically, the definition of cur_name and the incrementing of the pointer for cur_age in the printf statement.

*(cur_age + i)必须在索引数组中的每个整数,但是我希望它指向内存中的连续地址,而不是给定int为4个字节的下一个整数?即为什么不选择i + 4

*(cur_age + i) must be indexing each of the integers in the array but I would have expected this to point to successive addresses in memory and not the next integer given ints are 4 bytes? i.e. why not i+4

#include <stdio.h>

int main(int argc, char *argv[])
{
    int ages[] = {23, 43, 12, 89};
    char *names[] = {"Anne", "Kay", "Joe", "Pete"};
    int count  = sizeof(ages) / sizeof(int);
    int *cur_age = ages;
    char **cur_name = names;

    for (int i = 0; i < count; i++) {
        printf("%s is %d years old.\n", *(cur_name + i), *(cur_age + i));
    }

    return 0;
}

推荐答案

这只是在C中定义指针算术的方式.递增指针通常被认为是单位递增,其中一个单位是类型的sizeof()被指向.

This is simply how the pointer arithmetics is defined in C. Incrementing the pointer always considered to be incrementation in units, where one unit is the sizeof() of type being pointed to.

旁注-尽管int的大小通常为 4个字节,但这并不是一成不变的.它们也可能更小(2个字节)或更长(真的不是限制).

Side note - while int's are commonly 4 bytes in size, this is not set in stone. They might as well be smaller (2 bytes) or longer (really not limit).

这篇关于C数组中的增量指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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