我正在探索 C/C++ 中的指针“机制”。我尝试了解是否以及如何使用两个指针(一个用于“行”,一个用于“列”)而不是单个双指针来实现二维矩阵。我知 Prop 有行*列数的值的矩阵可以按顺序存储在内存中,但我希望更深入地理解指针的机制,并最终实现类似于
int value=getValue(vectorNr,vectorValue)
能够“模拟”构造
value=Matrix[vectorNr][vectorValue]
vectorPointer vectorValue
| AddressV1 |------|valAddr11 valAddr12 valAddr13 |
| AddressV2 |------|valAddr21 valAddr22 valAddr23 |
| AddressV3 |------|valAddr31 valAddr32 valAddr33 |
我尝试开始编写这样的代码,但我很快就陷入了指针算术和地址偏移的困境。我也可能选择了一种非常肮脏的方法,所以欢迎任何评论。
使用指针实现二维数组的代码(但不使用双指针)。为了避免行和列之间的混淆,我将“vector 作为行”和“列作为 vector 值”
int vectorsNumber = 3; //Number of Vectors
int valuesNumber = 3; //Number of values stored in one Vector
//Addresses of Vectors. Since Vectors holds a reference to set of values, vectorPointer will hold an address for every set.
void* vectorPointer = malloc(vectorsNumber *sizeof(void*));
//Populating the vectorPointer with the address generated by allocating memory for every set of values
for (int i = 0; i < vectorsNumber; i++)
{
vectorPointer = (int*)malloc(valuesNumber * sizeof(int)); //Values shall be of int types
vectorPointer++; //ILLEGAL since cannot perform arithmetic on pointers of type void. What do do??
}
//Restore the initial address. In any case...ILLEGAL arithmetic. What do do??
for (int i = 0; i < vectorsNumber; i++)
{
vectorPointer--; //Restore the initial address. In any case...ILLEGAL arithmetic.
}
//Declaring the pointer to hold the address of one value. Memory was already allocated before
int* valueAddress;
for (int j = 0; j < vectorsNumber; j++)
{
//Getting the address of the first value of the first Vector
valueAddress = (int*)vectorPointer; //Is this casting valid in C language?
//Populating the value with whatever operation
for (int k = 0; k < valuesNumber; k++)
{
*valueAddress = (k + 1)*(j + 1); //populate the Vector with int values
}
vectorPointer++; //Switch to next Vector.ILLEGAL arithmetic
}
最佳答案
实际上,你只需要一个指针。一种方法是分配足够的内存来保存所有值,然后使用函数将数组中的 x/y 值映射到相应的内存位置。假设我们希望这些是维度和数组变量:
int dimX = 10, dimY = 5;
int *array;
您可以这样设置值:
void arraySet(int value, int x, int y) {
array[x + dimX * y] = value;
}
并以这种方式获取值:
int arrayGet(int x, int y) {
return array[x + dimX * y];
}
预先分配内存,例如在main
函数中:
array = malloc(sizeof(int)*dimX*dimY);
像这样使用它:
arraySet(123, 9, 3); // sets the value of [9, 3] to 123
printf("Memory at 9, 3 is %d\n", arrayGet(9, 3));
关于c - 在 C/C++ 中 : How can i implement a 2D int array using two single pointers (no use of **int)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55256603/