c - 为 C 中的动态二维数组赋值时出现段错误

标签 c memory dynamic segmentation-fault

您好,我正在用 C 语言编写程序,但是在运行我的程序时遇到了段错误。

我正在使用 gcc 进行编译,并且在编译时没有给出任何警告或错误。

我尝试使用 gdb 来追踪段错误的起源,它指引我到我将数据值分配给我的二维数组的那一行: 数组[行][列] = 数据值;

当我运行我的程序时,存储了 3 个数据值,然后出现段错误。它应该存储 424 行 x 117 列的数据,但它在仅存储 3 个数据值后始终会出现故障。

我的代码如下(省略了一些细节):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void allmem(float** fpdata,...);            // allocate memory header
void stored(float** fpdata,...);            // store data header
void countnumber(int* num1, int*num2,...);  // count header

int main()   // main() function
{
int numberofrows = 424; // number of rows
float** fpdata;         // two dimensional array fpdata of floats

allmem(fpdata,...);     // call allocate memory function
stored(fpdata,...);     // call function to store data
...
return 0;
} // main ()

// --------------stored() function---------------
void stored(float** fpreal,...) {

FILE *fp;                  // file pointer
float datavalue;           // variable to hold data values read
int row;
int column;

fp = fopen("c:/file.txt","r");

for(column = 0; column < 117; column++) {
  for(row = 0; row < 424; row++) {
    fscanf(fp, "%f,", &datavalue);
    fpdata[row][column] = datavalue;
  } // for
} // for  
fclose(fp);
} // stored()

// ----------allmem() function----------------
// function to allocate memory for two dimensional arrays
// I have hard coded the values of the array sizes in, but
// in my actual program they are calculated at run time based
// on the size of some input files and this is done in the 
// countnumber() function

void allmem(float** fpdata,...) {
int i = 0;
fpdata = (float**) malloc((424)*sizeof(float*));
fpdata2 = (float**) malloc((424)*sizeof(float*));
...
for (i = 0; i<424; i++) {
  fpdata[i] = (float*) malloc((117)*sizeof(float));
  fpdata2[i] = (float*) malloc((117)*sizeof(float));
} // for

} // allmem()

最佳答案

fpdata 是按值传递的,而不是按指针或引用传递的。这意味着当函数从 allmem 返回时,fpdata 仍然指向它之前所做的相同事情并且分配的内存丢失。

您需要调用 allmem(&fpdata,...);

并使用函数签名void allmem(float*** fpdata,...)

然后,在 allmem 中,设置 *fpdata = (float**)...

当然,(*fpdata)[i] = (float*) malloc... 在“for”循环中。

编辑:

我希望您对 fpdata2 做同样的事情。但是您不必更改 stored() 中的任何内容(尽管看起来您传入了 fpreal 但将值分配给 fpdata 这是可能只是一个简化的代码错误?)。传递给 stored 的指针应该是有效的。您并不是要更改 stored 中的指针,只是更改它指向的内存中的值。

关于c - 为 C 中的动态二维数组赋值时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5520402/

相关文章:

c++ - 0x771CC7C9 (ntdll.dll) 处未处理的异常

c - Scanf 带有格式说明符和输入不匹配

c - 通过 SWIG 输入 Python 3 个字节到 C char*

c - 使用 char[] 获取可变大小的 C 可变参数

winapi - 扫描电脑内存

c# - 应用程序的内存搜索索引占用太多内存 - 有什么建议吗?

php - 如何在 URL 中放置 MySQL 行数据?

c - 尝试使用 for 循环初始化 1G 内存时访问内存崩溃

java - UseCompressedOops JVM 标志有什么作用以及何时应该使用它?

ios - 在动态创建的 uibuttons 上未检测到单击