我有一个二维数组指针的问题.指针应指向可变大小的数组.
// create pointer to 2 dimensional array
TimeSlot **systemMatrix; // this is a global variable
Run Code Online (Sandbox Code Playgroud)
在一个函数中我想创建一个新数组.
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
}
Run Code Online (Sandbox Code Playgroud)
但是当我让指针指向数组时,编译器会说"警告:从不兼容的指针类型中分配".此外,当从另一个函数访问systemmatrix [2] [5]时,运行软件的mikrocontroller会出现硬故障.
稍后在访问tmpTimeSlots的元素时需要变量systemMatrix.
我试过像这样的组合
systemMatrix = *(*tmpTimeSlot);
Run Code Online (Sandbox Code Playgroud)
等等,但它们似乎都没有用.
任何帮助表示赞赏:)谢谢!
编辑:好的问题理解和解决,非常感谢!
小智 6
二维数组!=双指针.
你几乎肯定需要动态内存分配.您还希望深度复制数组的内容 - 它是一个非静态局部变量,因此它的范围无效.你无法做到TYPE arr[sz]; return arr;这一点.
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];
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6570 次 |
| 最近记录: |