C指针,指向2维数组 [英] C pointer to 2 dimensional array

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

问题描述

我有一个指针二维数组的问题。指针应指向可变大小的阵列。

I've got problems with a pointer to a two dimensional array. The pointer shall point to an array of variable size.

// create pointer to 2 dimensional array
TimeSlot **systemMatrix; // this is a global variable

在一个函数,我想创建一个新的数组。

In a function I want to create a new array.

void setup(uint16_t lines, uint16_t coloumns) {
    // create 2 dimensional array. size can be set here.
    TimeSlot tmpTimeSlots[lines][coloumns];

    // make the pointer point to this array
    systemMatrix = tmpTimeSlots; // WARNING
}

但是,当我让指针指向数组编译器说:警告:从分配不兼容的指针类型。此外,这里的软件应上运行mikrocontroller访问systemmatrix时得到一个硬故障。[2] [5]从另一个功能

But when I let the pointer point to the array the compiler says "warning: assignment from incompatible pointer type". In addition, the mikrocontroller where the software shall run on gets a hard fault when accessing systemmatrix[2][5] from another function.

访问tmpTimeSlots的元素时以后需要的变量systemMatrix。

The variable systemMatrix is needed later when accessing the elements of tmpTimeSlots.

我试着像

systemMatrix = *(*tmpTimeSlot);

等等,但他们都不工作。

and so on but none of them seem to work.

任何帮助是AP preciated :)
谢谢!

Any help is appreciated :) Thanks!

编辑:!还好问题的理解和解决,非常感谢

okay problem understood and solved, thanks a lot!

推荐答案

二维数组!=双指针。

您几乎肯定需要为这个动态内存分配。你也想​​深副本的阵列中的内容 - 这是一个非静态局部变量,所以它是无效的其范围。你不能做 TYPE ARR [深圳]回改编; 作为一个后果

You almost certainly need dynamic memory allocation for this. You also want to deep copy the contents of the array - it's a non-static local variable, so it's invalid out of its scope. You can't do TYPE arr[sz]; return arr; as a consequence.

const size_t width = 3;
const size_t height = 5;
TimeSlot tmpTimeSlot[width][height];

systemMatrix = malloc(width * sizeof systemMatrix[0]);
for (int i = 0; i < width; i++) {
    systemMatrix[i] = malloc(height * sizeof systemMatrix[i][0]);
    for (int j = 0; j < height; j++) {
        systemMatrix[i][j] = tmpTimeSlot[i][j];
    }
}

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

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