其元素指向另一个指针数组的指针数组

时间:2021-06-09 06:59:19

标签: arrays c pointers

我非常需要的是一个数组 A[10] 并且它的每个元素都指向数组 B[10] 的各个元素,其每个元素都存储其索引。

因此,A[1] 指向 B[1]B[1] 的值为 1。 因此,当我调用 *A[1]*B[1] 时,我得到 1。

我知道如果数组 B[10] 不是指针数组而是整数数组,这会非常容易,但我需要它用于其他目的。

这是我所做的,但提供了分段错误。

#include <stdio.h>

int main() {
    int *A[10];
    int *B[10];
    
    for(int i=0; i<10; i++) {
        A[i] = B[i];
        *B[i] = i;
        printf("\n%d %d",*A[i],*B[i]);
    }
}

顺便说一句,我不是很精通指针。

1 个答案:

答案 0 :(得分:3)

您评论的代码:

int main() {
    int *A[10];   // an array of 10 pointers, each of them pointing nowhere
    int *B[10];   // an array of 10 pointers, each of them pointing nowhere

    // now each array a and b contain 10 uninitialized pointers,
    // they contain ideterminate values and they point nowhere
    
    for(int i=0; i<10; i++) {
        A[i] = B[i];     // copy an uninitialized pointer
                         // this usually works but it's pointless

        *B[i] = i;       // you assign i to the int pointed by *B[i]
                         // but as *B[i] points nowhere you end up with a segfault

        printf("\n%d %d",*A[i],*B[i]);  // you never get here because the previous
                                        // line terminates the program with a segfault,
                                        // but you'd get a segfault here too for 
                                        // the same reason
    }
}

你的程序基本上是这样的:

int main() {
    int *a;     // a is not initialized, it points nowhere
    *a = 1;     // probably you'll get a segfault here
}

访问一个指针所指向的事物称为解除对指针的引用。取消引用一个未初始化的指针会导致未定义的行为(谷歌那个词),很可能你会得到一个段错误。

我不确定你想要达到什么目的,但你可能想要这样的东西:

#include <stdio.h>

int main() {
  int* A[10];
  int B[10];

  for (int i = 0; i < 10; i++) {
    A[i] = &B[i];
    B[i] = i;
    printf("%d %d\n", *A[i], B[i]);
  }
}