c - C 中的指针数组

标签 c arrays pointers for-loop

代码已根据以下答案和反射(reflect)的警告/问题进行了更新

我正在尝试用 C 编写指针数组。一个循环设置值,另一个循环检索它们 - 非常简单。以下是我尝试设置这些值的方式:

static int  *toInvert[8];
for (i=0; i<8; i++)
{
              int *intrplated = //Function call that returns int*
              toInvert[i] = intrplated;
              //printf("OL Value = %d\n\n\n\n\n",oLoop);
}

为了检索值,这里是没有循环的代码,即检索固定值:

int *tmpPtr = toInvert[3]; 
printf( "*(TPointer + %d) : %d\n\n", 3, *(toInvert[3] + 1)); //Still gives the recently added value

当我尝试打印值时,只打印了 setter 循环中最后添加的值。即使我将 tmpPtr 更改为 toInvert[1],它仍会获得最后设置的值。

但如果我在编写的 for 循环中运行相同的代码,它会按预期工作。

我需要知道如何检索所有已设置的值。谢谢

编辑 我想要的是一个包含 8 个指针的 8 个元素的数组。每个指针依次指向一个包含 3 个普通整数的数组。 我想要的数组应该类似于 [p1][p2]...[p8],其中 [p1] 指向一个整数数组。

最佳答案

您要实现的是一个指针数组,对吗?

#include <stdio.h>
#include <stdlib.h>
#define LIMIT 3

int main()
{
    int i,j;
    static int  *toInvert[LIMIT];
    int *intrplated;
    for (i=0; i<LIMIT; i++)
    {
        intrplated = malloc(sizeof(int)*5);
        intrplated[0] = rand();
        intrplated[1] = rand();
        intrplated[2] = rand();
        intrplated[3] = rand();
        intrplated[4] = rand();
        toInvert[i] = intrplated;
    }
    for (i=0;i<LIMIT;i++)
    {
        printf("Tpointer to toInvert[%d] contains::\t [",i);
        for(j=0;j<5;j++)
        {
            printf("%d ",toInvert[i][j]);
        }
        printf("]\n");
    }

    putchar('\n');
    for(j=0;j<5;j++)
    {
        printf("%d ",toInvert[1][j]);
    }
    putchar('\n');
    for(i=0;i<LIMIT;i++)
    {
        free(toInvert[i]);
    }
    return 0;
}

在 GCC 4.8.0 上编译

编辑:看到变化,指针数组保留了信息

输出:

Tpointer to toInvert[0] contains::       [41 18467 6334 26500 19169 ]
Tpointer to toInvert[1] contains::       [15724 11478 29358 26962 24464 ] 
Tpointer to toInvert[2] contains::       [5705 28145 23281 16827 9961 ]

15724 11478 29358 26962 24464

关于c - C 中的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16243046/

相关文章:

c - C中整数集合的简单实现

c++ - 使用函数c++查找数组中的元素

c - c 中的指针和 c 程序

c++ - 如何检索智能指针数组的大小? (例如 std::unique_ptr<int[]>)

arrays - 如何在 Angular 4 中将对象转换为数组?

c++ - 如何使用数组按引用对对象进行排序? (以一种不那么愚蠢/复杂的方式。)

c - 错误: expected primary-expression before "__attribute__"; error: expected ';' before "__attribute__"

OpenMP 可能无法直接并行化的代码

c - setjmp 和 GCC 的合法使用

c - 无法在 If 语句中检索或存储二维数组位置