我在结构中创建二维数组时遇到问题。到目前为止,这是我的代码,但我确定它是错误的数组存储在结构中的 char 指针中,但数组必须用于 float ,所以这也让我感到困惑:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ROWS 5000
#define MAX_COLUMNS 5000
struct array
{
int rows;
int columns;
int order;
char *base_pointer; /* pointer to array of bytes. In this array, float numbers will be stored (4 bytes each) */
};
struct array* initialize(int rows, int columns, int order)
{
/* Allocate the required memory for the 2D array to store float values (Ex: 1.45) with "rows" and "columns" */
struct array* array = (struct array*)malloc(rows * columns);
/* Make sure the size is within 1 to MAX_ROWS and 1 to MAX_COLUMNS specified in main.c. If not return null pointer */
array->rows = rows;
array->columns = columns;
array->order = order;
/* Initialize the 2D array to the all zeroes (0.0) */
/* Assign suitable values to all the elements of the structure and return the struct pointer */
return array;
}
最佳答案
我想这就是您要找的:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ROWS 5000
#define MAX_COLUMNS 5000
struct array
{
int rows;
int columns;
int order;
char *base_pointer; /* pointer to array of bytes. In this array, float numbers will be stored (4 bytes each) */
};
struct array* initialize(int rows, int columns, int order)
{
int i,
size = columns * rows * sizeof(float);
/* Allocate the required memory for the 2D array to store float values (Ex: 1.45) with "rows" and "columns" */
// If you want to allocate both the structure and the internal storage in one malloc:
/*
struct array* array = (struct array*) malloc(sizeof(struct array) + size);
array->base_pointer = &((char*)array)[sizeof(struct array)];
*/
struct array* array = malloc(sizeof(struct array));
if(!array) {
return 0; // error
}
array->base_pointer = malloc(size);
if(!array->base_pointer) {
return 0; // error
}
for(i = 0; i < size; i++) {
array->base_pointer[i] = 0;
}
/* Make sure the size is within 1 to MAX_ROWS and 1 to MAX_COLUMNS specified in main.c. If not return null pointer */
array->rows = rows;
array->columns = columns;
array->order = order;
/* Initialize the 2D array to the all zeroes (0.0) */
/* Assign suitable values to all the elements of the structure and return the struct pointer */
return array;
}
void insert(struct array* arr, int row, int column, float value) {
float* floatArr = (float*)arr->base_pointer;
floatArr[(column * arr->rows) + row] = value;
}
float retrieve(struct array* arr, int row, int column) {
float* floatArr = (float*)arr->base_pointer;
return floatArr[(column * arr->rows) + row];
}
您正在为内部数组分配所需的内存,并试图将其用于结构。相反,您需要为该结构分配内存,然后为其内部数组 base_pointer
提供指向单独分配的指针。
关于c - 线性存储器中的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24917310/