C 指向结构的自由三维指针
我有一个结构地球仪,它包含地球仪上每个lat-lon单元的几个参数。 我有一个三重指针,如下所示:C 指向结构的自由三维指针,c,pointers,C,Pointers,我有一个结构地球仪,它包含地球仪上每个lat-lon单元的几个参数。 我有一个三重指针,如下所示: data->map = (struct GLOBE ***)malloc_2d(NROWS, NCOL, sizeof(struct GLOBE *)); struct GLOBE { double *var; }; 其中malloc_2d是一个自定义函数,用于分配下面定义的2d数组。地图可以在全球范围内进行迭代 void** malloc_2d (size_t nrows, siz
data->map = (struct GLOBE ***)malloc_2d(NROWS, NCOL, sizeof(struct GLOBE *));
struct GLOBE {
double *var;
};
其中malloc_2d是一个自定义函数,用于分配下面定义的2d数组。地图可以在全球范围内进行迭代
void** malloc_2d (size_t nrows, size_t ncols, int elementsize) {
size_t i;
void ** ptr;
if ( (ptr = (void**)malloc(nrows * sizeof(void *))) == NULL ) {
fprintf(stderr, "malloc_2d: out of memory\n");
exit(1);
}
if ( (ptr[0] = malloc(nrows * ncols * elementsize)) == NULL ) {
fprintf(stderr, "malloc_2d: out of memory\n");
exit(1);
}
for (i=1; i<nrows; i++)
ptr[i] = (char*)ptr[0] + i * ncols * elementsize;
return ptr;
void**malloc\u 2d(大小\u t nrows、大小\u t ncols、内部元素大小){
尺寸i;
无效**ptr;
if((ptr=(void**)malloc(nrows*sizeof(void*)))==NULL){
fprintf(stderr,“malloc_2d:内存不足\n”);
出口(1);
}
if((ptr[0]=malloc(nrows*ncols*elementsize))==NULL){
fprintf(stderr,“malloc_2d:内存不足\n”);
出口(1);
}
对于(i=1;i而言,malloc_2d()
(复制粘贴?)函数的编写似乎是正确的,但此处发布的其余代码完全不是这些
我将在这里发布一个类似于您想要做的事情的工作示例,在这里使用enter codemalloc_2d()
。我建议您使用它,直到您了解C中指针的基本概念
此外,请随意询问(明确)有关代码的问题
#include <stdio.h>
#include <stdlib.h>
#define NROWS 8
#define NCOL 6
struct GLOBE {
double **var;
};
void** malloc_2d (size_t nrows, size_t ncols, int elementsize)
{
// code posted
}
void free_2d (void ** ptr, size_t n_rows)
{
int i;
// free the "big part"
free(ptr[0]);
// free the array of pointers to the rows
free(ptr);
}
int main()
{
struct GLOBE gl;
int i, j;
gl.var = (double **)malloc_2d(NROWS, NCOL, sizeof(double));
for (i = 0; i < NROWS; ++i) {
for (j = 0; j < NCOL; ++j) {
gl.var[i][j] = i * j;
printf("%0.1f ", gl.var[i][j]);
}
printf("\n");
}
free_2d((void **)gl.var, NROWS);
return 0;
}
#包括
#包括
#定义NROWS 8
#定义NCOL6
结构球{
双**var;
};
void**malloc\u 2d(尺寸箭头、尺寸图标、内部元素尺寸)
{
//代码发布
}
无空隙\u 2d(空隙**ptr,大小\u t n行)
{
int i;
//释放“重要部分”
自由(ptr[0]);
//释放指向行的指针数组
免费(ptr);
}
int main()
{
结构GLOBE-gl;
int i,j;
gl.var=(双**)malloc_2d(NROWS、NCOL、sizeof(双));
对于(i=0;i
您需要在此处发布更多代码,包括GLOBE
结构的定义和malloc_2d
数组的实现。您的代码…“感觉很奇怪”…修改代码以包含malloc_2d和GLOBE的定义
#include <stdio.h>
#include <stdlib.h>
#define NROWS 8
#define NCOL 6
struct GLOBE {
double **var;
};
void** malloc_2d (size_t nrows, size_t ncols, int elementsize)
{
// code posted
}
void free_2d (void ** ptr, size_t n_rows)
{
int i;
// free the "big part"
free(ptr[0]);
// free the array of pointers to the rows
free(ptr);
}
int main()
{
struct GLOBE gl;
int i, j;
gl.var = (double **)malloc_2d(NROWS, NCOL, sizeof(double));
for (i = 0; i < NROWS; ++i) {
for (j = 0; j < NCOL; ++j) {
gl.var[i][j] = i * j;
printf("%0.1f ", gl.var[i][j]);
}
printf("\n");
}
free_2d((void **)gl.var, NROWS);
return 0;
}