我正在使用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()中完成() –