【发布时间】:2012-12-20 14:11:11
【问题描述】:
请考虑以下代码:
#include <stdio.h>
#include <stdlib.h>
#define NUM_ARRAYS 4
#define NUM_ELEMENTS 4
#define INVALID_VAL -1
int main()
{
int index = INVALID_VAL;
int array_index = INVALID_VAL;
int **ptr = NULL;
ptr = malloc(sizeof(int*)*NUM_ARRAYS);
if (!ptr)
{
printf ("\nMemory Allocation Failure !\n\n");
exit (EXIT_FAILURE);
}
for (index=0; index<NUM_ARRAYS; index++)
{
*(ptr+index) = malloc(sizeof(int)*NUM_ELEMENTS);
if (!*(ptr+index))
{
printf ("\nMemory Allocation Failure !\n");
exit (EXIT_FAILURE);
}
}
/* Fill Elements Into This 2-D Array */
for (index=0; index<NUM_ARRAYS; index++)
{
for (array_index = 0; array_index<NUM_ELEMENTS; array_index++)
{
*(*(ptr+index)+array_index) = (array_index+1)*(index+1);
}
}
/* Print Array Elements */
for (index = 0; index<NUM_ARRAYS; index++)
{
printf ("\nArray %d Elements:\n", index);
for (array_index = 0; array_index<NUM_ELEMENTS; array_index++)
{
printf (" %d ", *(*(ptr+index)+array_index));
}
printf ("\n\n");
}
return 0;
}
我的代码没有问题。它工作正常。
Output:
Array 0 Elements:
1 2 3 4
Array 1 Elements:
2 4 6 8
Array 2 Elements:
3 6 9 12
Array 3 Elements:
4 8 12 16
我有一个关于指针运算的问题:
*(ptr+0) = 指向 COMPLETE BLOCK(第一个数组)的指针*(ptr+1) = 指向 COMPLETE BLOCK(第二个数组)的指针。
但什么是:(*ptr+1)?
GDB 输出:
(gdb) p *(*ptr+1)
$1 = 2
(gdb) p *(*ptr+2)
$2 = 3
(gdb) p *(*ptr+3)
$3 = 4
(gdb) p *(*ptr+4)
$4 = 0
我对此感到困惑。请给我一些解释来解决这个疑问。
【问题讨论】:
-
我在这段代码中没有看到
(*ptr+1)。 -
不,它不存在。这是我编写此代码后的概念怀疑
标签: c multidimensional-array double-pointer