Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 用指针算法迭代结构数组_C_Arrays_Struct_Pointer Arithmetic - Fatal编程技术网

C 用指针算法迭代结构数组

C 用指针算法迭代结构数组,c,arrays,struct,pointer-arithmetic,C,Arrays,Struct,Pointer Arithmetic,我正试图通过指针算法迭代结构数组。然而,它给我的结果,我不能理解 #include <stdio.h> #include <stdlib.h> typedef struct { int hours; int minutes; int seconds; } Time; void time_print(Time t) { printf("Time is: %d:%d:%d\n", t.hours, t.minutes, t.seconds)

我正试图通过指针算法迭代结构数组。然而,它给我的结果,我不能理解

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

typedef struct
{
    int hours;
    int minutes;
    int seconds;
} Time;

void time_print(Time t)
{
    printf("Time is: %d:%d:%d\n", t.hours, t.minutes, t.seconds);
}

int main(void)
{    
    Time *testTimePointers[2];

    testTimePointers[0] = malloc(sizeof(Time));
    testTimePointers[0]->hours = 11;
    testTimePointers[0]->minutes = 10;
    testTimePointers[0]->seconds = 9;

    testTimePointers[1] = malloc(sizeof(Time));
    testTimePointers[1]->hours = 7;
    testTimePointers[1]->minutes = 6;
    testTimePointers[1]->seconds = 5;

    time_print(*(testTimePointers[0]));
    time_print(*(testTimePointers[1]));

    printf("=============\n");


    Time *ttp_cur = NULL;
    ttp_cur = testTimePointers[0];

    time_print(*(ttp_cur));

    ttp_cur++;

    time_print(*(ttp_cur));


    free(testTimePointers[0]);
    free(testTimePointers[1]);

    return 0;
}

在第二个块中,第二行应该是
Time is:7:6:5
,而不是
Time is:0:0

问题是您试图增加一个不指向数组的指针
ttp\u cur

您试图增加的值,
ttp\u cur
,来自
testTimePointers[0]
,它又来自单个
struct Time
malloc
,而不是数组。这就是为什么当您递增该指针时,行为是未定义的

但是,可以增加指向
testTimePointers
数组的指针。如果你这么做了

Time **ttp_cur_p = testTimePointers;
time_print(*(*ttp_cur_p));
ttp_cur_p++;
time_print(*(*ttp_cur_p));

你会得到你期望的结果()。

我认为在程序的第二部分中,你指的是以下内容

    //...

    Time **ttp_cur = testTimePointers;

    time_print(**ttp_cur );

    ttp_cur++;

    time_print(**ttp_cur);


    free(testTimePointers[0]);
    free(testTimePointers[1]);

    return 0;
}
如果你有一个像

T a[2];
如果
T
是某种类型说明符,那么指向其第一个元素的指针按以下方式声明

T *p = a;
和表达

++ttp_cur;
++p

将指向数组的第二个元素

现在如果考虑你的数组

Time *testTimePointers[2];
然后类型说明符
T
将等于
Time*
。因此,指向数组第一个元素的指针的声明如下

Time **ttp_cur = testTimePointers;
和表达

++ttp_cur;

将指向数组的第二个元素。

ttp_cur++之后指针使步长等于sizeof(时间)并指向任何地方。