指针数组的问题,高手帮我看看啊
大家好,我编下面的代码时会报“非法索引,不允许间接寻址”的错,请问有什么好办法能解决这个问题吗?
AVCodecContext** aCodecCtx = new AVCodecContext*[tracksIndex];
AVCodec** aCodec = new AVCodec*[tracksIndex];
for(i = 0;i < tracksIndex;i++)
{
aCodecCtx[i] = ic->streams[audioindex]->codec;
aCodec[i] = avcodec_find_decoder( aCodecCtx->codec_id );
if( avcodec_open(aCodecCtx[i],aCodec[i] ) < 0 )
{
strMsg.Format( _T("can't open the #%d audio decoder"),i );
AfxMessageBox( strMsg );
return-1;
}
}
[解决办法]
for()
aCodecCtx [i] = new xxxx
aCodec [i] = new xxx
//两维数组,要对每一个进行申请空间。。
[解决办法]
提醒一句:使用数组与指针问题,要格外小心!
尤其越界问题,是运行崩机,内存错误一大来源。
[解决办法]
指针的实质 其本身就是一个 int变量,对于 AVCodecContext* 这种类型的指针他也仅仅是一个int变量而已,不关心其指向的内容的类型。
测试用例如下:
1 #include <iostream> 2 using namespace std; 3 4 class testClass 5 { 6 private: 7 int a; 8 int b; 9 }; 10 11 int main() 12 { 13 testClass A; 14 testClass** ppA = new testClass*[5]; 15 testClass* testpA = new testClass; 16 ppA[3] = testpA; 17 cout<<ppA[3]<<"bijiao" <<testpA; 18 return 0; 19 }
[解决办法]
//在堆中开辟一个4×5的二维int数组#include <stdio.h>#include <malloc.h>int **p;int i,j;void main() { p=(int **)malloc(4*sizeof(int *)); if (NULL==p) return; for (i=0;i<4;i++) { p[i]=(int *)malloc(5*sizeof(int)); if (NULL==p[i]) return; } for (i=0;i<4;i++) { for (j=0;j<5;j++) { p[i][j]=i*5+j; } } for (i=0;i<4;i++) { for (j=0;j<5;j++) { printf(" %2d",p[i][j]); } printf("\n"); } for (i=0;i<4;i++) { free(p[i]); } free(p);}// 0 1 2 3 4// 5 6 7 8 9// 10 11 12 13 14// 15 16 17 18 19