帮助我解决C中的内存访问冲突错误 [英] Help me for an memory access violation error in C
问题描述
我得到内存访问冲突错误,请快速帮帮我!!!!
我写了这样的代码,请注意我的评论错误行
I get memory access violation error, please help me quickly!!!!
I wrote a code like this, kindly note my commented line of error
float fValue=0;
stpData ->dbpMG1G1_data = ( float ** ) malloc (sizeof ( float * ) * nRows * nColumns);
while ( NULL != fgets( cpReadString, 6144, fStream ) && nRow < nRows )
{
while ( NULL != cpSubString && nColumn < nColumns )
{
fValue = atof(cpSubString) ;
stpData ->dbpMG1G1_data[nRow][nColumn] = fValue ; // here I am getting error
++nColumn ;
}
++nRow ;
}
我在外面写了内存分配代码行循环以便
优化执行速度。是索引问题还是别的?
完成调试错误通知:
I delibratly wrote the memory allocation code line outside the loops so as to
optimze the execution speed. Is it indexing problem or something else?
Complete debugg error notification:
Unhandled exception at 0x0042b9e2 in On_The_Fly-A350.exe: 0xC0000005: Access violation writing location 0xcdcdcdcd.
提前致谢!!!!!!!
Thanks in advance!!!!!!!
推荐答案
你需要一个浮点矩阵(你不需要(nRows * nColumns)
的float 指针)。
我认为一个简单的方法是(使用数据
而不是stpData - > dbpMG1G1_data
来简化符号):
You need a matrix of floats (you don''t need(nRows * nColumns)
of float pointers).
I think an easy approach would be (usingdata
instead ofstpData ->dbpMG1G1_data
to simplify notation):
data = (float *) malloc( sizeof(float) * nRows * nColumns); // linear array of floats
//..
{
fValue = atof(cpSubString) ;
int i = nRow * Columns + nColumn; // bidimensional to linear: [Row][Column] => [i]
data[i] = fValue;
}
您正在分配一个带有nRows的一维数组
*nColumns
指向float
的指针元素并将其转换为float **
。这不起作用(在这种情况下,总数组大小将匹配浮点数,因为32位构建的sizeof(float)== sizeof(float *),但访问2-dim成员将导致访问冲突)。
要解决此问题,您有两种选择:
1.使用一维数组并计算索引访问元素时:
You are allocating an 1-dimensional array withnRows
*nColumns
elements of pointers tofloat
and casting this to afloat**
. This will not work (the total array size would match for floats in this case because sizeof(float) == sizeof(float *) for 32-bit builds, but accessing 2-dim members will cause access violations).
To fix the problem, you have two options:
1. Use a 1-dimensional array and calculate the index when accessing elements:
stpData->dbpMG1G1_data = (float *)malloc(sizeof(float) * nRows * nColumns);
// ...
stpData ->dbpMG1G1_data[nRow * nColumns + nColumn] = fValue;
1.使用必须使用循环分配的二维数组:
1. Use a 2-dimensional array which must be allocated using a loop:
stpData->dbpMG1G1_data = (float **)malloc(sizeof(float *) * nRows);
int i;
for (i = 0; i < nRows; i++)
stpData ->dbpMG1G1_data[i] = (float *)malloc(sizeof(float) * nColumns);
第一个版本的格式更多,不需要释放另一个循环中的内存。
The first version is more performat and does not require freeing the memory inside another loop.
这篇关于帮助我解决C中的内存访问冲突错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!