如何区分整数指针和整数数组指针 [英] how to differentiate integer pointer and integer array pointer

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

问题描述

我试图区分整数指针和整数数组指针,这是我用作示例的代码:

I was trying to differentiate integer pointer and integer array pointer and here's the code that I am using as an example:

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

#define ZLEN 5
typedef int zipdig[ZLEN] ;
#define UCOUNT 3
typedef int (*row5_pt)[ZLEN];

int main(int argc, char *argv[]) {
    zipdig cmu = {8, 5, 2, 1, 3};
    zipdig mit = {0, 2, 1, 3, 9};
    zipdig ucb = {9, 4, 7, 2, 0};

    int *univ[UCOUNT] = {mit, cmu, ucb};
    int result1 = *univ[1];

    row5_pt pt[UCOUNT] = {&mit, &cmu, &ucb};

    int result2 = (*pt[1])[1];

    printf("\nresult is %d \n", result1);
    printf("\nthe size of dereferenced univ is %lu bytes \n", sizeof(*univ[1]));

    printf("\nresult is %d \n", result2);
    printf("\nthe size of dereferenced pt is %lu bytes \n", sizeof(*pt[1]));


    return 0;
}

起初,我对以下两个作业感到困惑:

At first I am confused at the following two assignment:

int *univ[UCOUNT] = {mit, cmu, ucb};
row5_pt pt[UCOUNT] = {&mit, &cmu, &ucb};

这里,univ是3个整数指针的数组,而pt是指向5元素int数组的指针的数组.我的困惑是,在第一个作业mit,cmu和ucb中,这些数组标识符被视为指针,但是在第二个作业中,为什么mit,cmu和ucb被视为数组而不是指针?

here univ is an array of 3 integer pointers, and pt is an array of pointers that point to a 5-element int array. And my confusion is that in the first assignment, mit, cmu and ucb, these array identifiers are regarded as pointers, but when it comes to second assignment, why mit, cmu and ucb are regarded as array, not pointers?

后来我意识到这是由于使用的指针类型不同:第一次分配,univ的元素是整数指针,而mit,cmu,ucb恰好被视为整数指针,但是对于第二次分配, pt的元素是指向数组而不是整数的指针,因此我们不能直接使用mit,cmu或ucb,而必须使用其地址.

Later I realized that this is due to the different pointer type that I use: the first assignment, the element of univ is an integer pointer, and mit, cmu, ucb are exactly regarded as integer pointer, but for second assignment, the element of pt is a pointer pointing to array, not integers, thus we could not directly use mit, cmu or ucb but have to use their address instead.

我的理解正确吗?

推荐答案

是的,您的理解是正确的.

Yes, your understanding is correct.

原因是所涉及指针的类型. &mit是指向数组的指针,而mit(在表达式中)被转换为指向数组第一个元素的指针.

The reason is the type of the the pointers involved. &mit is a pointer to the array whereas mit (in an expression) is gets converted into a pointer to the array's first element.

int a[10];
int *p = a; // 'a' decays into a pointer to its first element i.e. &a[0]
int *q = &a[0]; // Equivalent to the above

int (*x)[10] = &a; // &a is of type int(*)[10] i.e. a pointer to an array of 10 ints

另请参阅:什么是阵列衰减?

这篇关于如何区分整数指针和整数数组指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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