【发布时间】:2016-04-23 05:19:29
【问题描述】:
我正在做一个用 C++ 编写的学校项目。我正在尝试根据用户输入为生成分形(无关)的程序生成一个 rgb 颜色数组。
我发现需要使用指向二维数组的指针。指针具有全局范围,因为它需要在多个文件、多个函数中访问。
指针的声明没有问题。是这样的:
在“global.h”中
int **ptr;
int palette[10][3];
//all the statements like #ifndef GLOBAL_H_INCLUDED, etc are present
在 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();
}
在 void 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 循环中],但是在输出它时 [最后一个 for 循环] 我得到了垃圾值。
从 cout 语句 [现在注释] 获得的输入数据 [正确值] 是 this [按列打印] 而给出的 O/P 是 this [按行打印] .
如果需要知道,“大小”(在这种情况下)=2,size_arr=256 和调色板[0]={0,0,255} 和调色板[1]={0,255,0}。
谁能指出问题出在哪里,是否与指针初始化有关?
【问题讨论】:
-
发布的代码无法编译。请发帖Minimal, Complete, and Verifiable example。
-
while(palette[i][0]!=256)i未初始化。 -
@PaulMcKenzie - 在 int main() 中完成
-
@Sh.A 在 int main() 中完成 -- 不,不是。
i是gen_array中的一个局部变量。 -
@PaulMcKenzie - 我改变了它[我的错]。我在发布问题时犯了一个错误。
标签: c++ arrays pointers dynamic multidimensional-array