在动态矩阵上设置指针 [英] Set pointers on Dynamic Matrix
问题描述
我正在尝试制作一个1字节元素的动态大小矩阵.为此,我定义了以下功能.当我尝试设置矩阵的第一个"nrows"元素指向相应的行时,问题就来了(所以我可以做matrix [i] [j]).看来matrix[i] = matrix[nrows + i * single_row_elements_bytes];
不能很好地工作(程序可以编译,但会引发核心段违规错误).我该如何进行这项工作?
I'm trying to make a dynamic size matrix of 1-byte elements. To do so I defined the following function. The problem comes when I try to set the first "nrows" elements of the matrix to point the corresponding row (so I can do matrix[i][j]). It looks like that matrix[i] = matrix[nrows + i * single_row_elements_bytes];
doesn't work well enough (the program compiles but throws an core-segment-violation error). How can I make this work?
uint8_t **NewMatrix(unsigned nrows, unsigned ncols)
{
uint8_t **matrix;
size_t row_pointer_bytes = nrows * sizeof *matrix;
size_t single_row_elements_bytes = ncols * sizeof **matrix;
matrix = malloc(row_pointer_bytes + nrows * single_row_elements_bytes);
unsigned i;
for(i = 0; i < nrows; i++)
matrix[i] = matrix[nrows + i * single_row_elements_bytes];
return matrix;
}
推荐答案
除了另一个答案中提到的各种错误之外,您还错误地分配了2D数组.实际上,您实际上根本没有分配2D数组,而是一个缓慢的,零散的查找表.
Apart from various bugs mentioned in another answer, you are allocating the 2D array incorrectly. You are actually not allocating a 2D array at all, but instead a slow, fragmented look-up table.
动态分配2D数组的正确方法在动态分配矩阵的功能中详细说明了它的工作方式以及数组指针的工作方式.
The correct way to allocate a 2D array dynamically is described at How do I correctly set up, access, and free a multidimensional array in C?. Detailed explanation about how this works and how array pointers work is explained at Function to dynamically allocate matrix.
以下是针对您的特定情况使用上述技术的示例:
Here is an example using the above described techniques, for your specific case:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <inttypes.h>
void NewMatrix (size_t nrows, size_t ncols, uint8_t (**matrix)[nrows][ncols])
{
*matrix = malloc ( sizeof (uint8_t[nrows][ncols]) );
}
int main (void)
{
size_t r = 3;
size_t c = 4;
uint8_t (*arr_ptr)[r][c];
NewMatrix(r, c, &arr_ptr);
uint8_t (*matrix)[c] = arr_ptr[0];
uint8_t count=0;
for(size_t i=0; i<r; i++)
{
for(size_t j=0; j<c; j++)
{
matrix[i][j] = count;
count++;
printf("%2."PRIu8" ", matrix[i][j]);
}
printf("\n");
}
free(arr_ptr);
}
这篇关于在动态矩阵上设置指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!