将指向内存缓冲区的指针转换为指向 VLA 的指针 [英] Casting pointer to memory buffer to pointer to VLA

查看:69
本文介绍了将指向内存缓冲区的指针转换为指向 VLA 的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 中,我相信以下程序是有效的:将指向已分配内存缓冲区的指针转换为这样的数组:

in C, I believe the following program is valid: casting a pointer to an allocated memory buffer to an array like this:

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

#define ARRSIZE 4

int *getPointer(int num){
    return malloc(sizeof(int) * num);
}

int main(){
    int *pointer = getPointer(ARRSIZE);
    int (*arrPointer)[ARRSIZE] = (int(*)[ARRSIZE])pointer;

    printf("%d\n", sizeof(*arrPointer) / sizeof((*arrPointer)[0]));

    return 0;
}

(输出 4).

但是,在 C99 中使用 VLA 执行此操作是否安全?

However, is it safe, in C99, to do this using VLAs?

    int arrSize = 4;
    int *pointer = getPointer(arrSize);
    int (*arrPointer)[arrSize] = (int(*)[arrSize])pointer;

    printf("%d\n", sizeof(*arrPointer) / sizeof((*arrPointer)[0]));

    return 0;

(也输出 4).

根据 C99 标准,这是否合法?

Is this legit, according to the C99 standard?

如果它是合法的,那就很奇怪了,因为这意味着 VLA 有效地启用了动态类型创建,例如 type(*)[variable] 类型的类型.

It'd be quite strange if it is legit, since this would mean that VLAs effectively enable dynamic type creation, for example, types of the kind type(*)[variable].

推荐答案

是的,这是合法的,是的,可变修改的类型系统非常有用.您可以使用自然数组语法访问连续的二维数组,其维度直到运行时才知道.

Yes, this is legit, and yes, the variably-modified type system is extremely useful. You can use natural array syntax to access a contiguous 2-D array both of whose dimensions were not known until runtime.

它可以被称为语法糖,因为没有它们你就无法使用这些类型做任何事情,但它可以使代码干净(在我看来).

It could be called syntactic sugar as there's nothing you can do with these types that you couldn't do without them, but it makes for clean code (in my opinion).

这篇关于将指向内存缓冲区的指针转换为指向 VLA 的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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