我正在使用C++编写一个学校项目。我正在尝试根据用户输入生成一个rgb颜色数组,以生成分形(不相关)的程序。动态初始化二维数组的输出错误
我发现需要使用指向二维数组的指针。指针具有全局范围,因为它需要在多个函数中的多个文件中访问。
指针声明没有问题。这是因为这样:
在 “global.h”
int **ptr;
int palette[10][3];
//all the statements like #ifndef GLOBAL_H_INCLUDED, etc are present
在空隙gen_array()的main.cpp
extern int **ptr;
extern int palette[10][3];
void gen_array();
int main()
{
//initialize values of palette
//palette is basically list of colors that the user selects for the
//desired blend of colors to appear on the screen
gen_array();
}
,在main.cpp中
void gen_array()
{
int i=0, size=0, size_arr=0;
//size is a variable helpful in calculating "size_arr", which is the size of the dynamic array to be initialized
while(palette[i][0]!=256)
{ //calculates "size" }
for(int i=0; i<size-1; i++)
{
//to find "size_arr"
}
ptr= new int*[size_arr]();
for(int i = 0; i < size_arr; ++i)
{
ptr[i] = new int[3];
}
//the following piece of code enter's values column-wise into the array
int s=0;
for(int i=0; i<size-1; i++)
{
for(int k=0; k<3; k++)
{
int x=-1, a=0, b=0;
a= palette[i][k] - palette[i+1][k];
b= palette[i][k];
if(a<0)
{
a= -a;
x=1;
}
for(int j=0; j<=a; j++, s++)
{
ptr[i][k] = b;
//cout<<*(*(ptr+i)+k)<<' ';
b= b+ x;
}
b= b-x;
for(int j=a+1; j<=diff[i]; j++, s++)
{
ptr[i][k] = b;
cout<<ptr[i][k]<<' ';
}
cout<<endl;
}
}
//this output's the array that the pointer points to, on the screen
for(int i=0; i<size_arr; i++)
{
for(int j=0; j<3; j++)
{
cout<<ptr[i][j]<<' ';
}
cout<<endl;
}
}
问题是,数据正在生成并正确输入阵列[在倒数第二个循环中],但输出时[最后一个for循环]我收到垃圾值。
从现在评论的cout语句获得的[正确值]输入的数据是this [打印的列],而输出的O/P是[打印的行] this。如果需要知道,“大小”(在这种情况下)= 2,size_arr = 256和调色板[0] = {0,0,255}和调色板[1] = {0,255,0} 。
任何人都可以指出问题是什么,以及它是否与指针初始化有关?
发布的代码不能编译。请发布[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。 –
'while(palette [i] [0]!= 256)''i'未初始化。 – PaulMcKenzie
@PaulMcKenzie -it在int main()中完成() –