为什么sizeof()对指针数组不起作用? [英] Why does sizeof() not work for pointer arrays?

查看:431
本文介绍了为什么sizeof()对指针数组不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
    int *pArray;
    int array[10];

    pArray = (int*)malloc( sizeof *pArray * 10 );

    int n = sizeof(pArray);
    int m = sizeof(array);

    printf("pArray size:\t%d\tarray size:\t%d\n", n, m);

    return 0;
}

在上面的代码中,指针数组的sizeof()操作的结果(其大小是使用malloc()分配的)的值为4,即单个元素的大小.但是,sizeof()函数会为普通数组返回正确的40值.

我总是听到数组只是C语言中的指针".如果数组和指针在功能上相同,为什么sizeof()无法与指针数组一起使用?

解决方案

它有效.宏

sizeof(pArray)

返回的是指针pArray的大小(在32位处理器上为4字节,在64位处理器上为8字节. /p>

这可能会有所帮助: https://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays

int main()
{
    int *pArray;
    int array[10];

    pArray = (int*)malloc( sizeof *pArray * 10 );

    int n = sizeof(pArray);
    int m = sizeof(array);

    printf("pArray size:\t%d\tarray size:\t%d\n", n, m);

    return 0;
}

In the code above, the result of the sizeof() operation for the pointer array, whose size was allocated using malloc(), is a value of 4, or the size of a single element. The sizeof() function, however, returns the correct value of 40 for the normal array.

I always hear "arrays are just pointers in C." If arrays and pointers are functionally identical, why does sizeof() not work with the pointer array?

解决方案

It does work. The macro

sizeof(pArray)

is returning the size of the pointer, pArray (which 4 bytes on a 32-bit processor and 8 bytes on a 64-bit processor.. Your quote, "arrays are just pointers in C" is not precisely correct.

This might help: https://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays

这篇关于为什么sizeof()对指针数组不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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