将指向指针数组的指针理解为函数中的参数 [英] Understanding pointer to pointer arrays as arguments in a function
问题描述
在尝试自己学习C的同时,我遇到了一个我想开发的简单程序.它只是试图利用指向指针数组的指针来制作类似于矩阵的东西.我在Windows上编译,运行时它崩溃了,与此同时,在Linux上尝试此代码时显示segmentation fault
,这是因为函数参数是数组吗?我在这里做什么错了?
While trying to learn C by myself, I came across this simple program that I want to develop. It just tries to make use of pointer to pointer arrays to make something that resembles matrices. I'm compiling on Windows and when I run it, it just crashes, meanwhile, trying this code on Linux it says segmentation fault
, is this because of the function arguments that are arrays? What am I doing wrong here?
#include <stdio.h>
#include <stdlib.h>
void initializeArray(float** array, int size);
void printArray(float** array, int size);
int main()
{
float** array_1 = NULL;
int array_size = 3;
initializeArray(array_1, array_size);
// Free memory from array
for (int i = 0; i < array_size; i++)
{
free(array_1[i]);
}
free(array_1);
return 0;
}
void initializeArray(float** array, int size)
{
array = malloc(size * sizeof(float*));
if (array)
{
for (int i = 0; i < size; i++)
{
array[i] = malloc(size * sizeof(float));
if (!array[i])
{
exit(0);
}
}
}
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
array[i][j] = 0;
}
}
}
void printArray(float** array, int size)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
printf("%f\t", array[i][j]);
}
printf("\n");
}
}
推荐答案
执行时:
void initializeArray(float** array, int size)
{
array = malloc(size * sizeof(float*));
您没有在函数外更改array
,因此array_1
在调用之后(如之前)指向NULL(并导致内存泄漏).您需要返回它(或将其作为三重***
指针传递并将其用作*array
,但这不太方便).
you're not changing array
outside the function so array_1
points to NULL after (like before) the call (and creates a memory leak). You need to return it (or to pass it as triple ***
pointer and use it as *array
, but that's less convenient).
float **initializeArray(int size)
{
float** array = malloc(size * sizeof(float*));
...
return array;
}
和来自主站:
array_1 = initializeArray(array_size);
这篇关于将指向指针数组的指针理解为函数中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!