【问题标题】:Array of pointers whose elements point to another array of pointers其元素指向另一个指针数组的指针数组
【发布时间】:2021-06-09 06:59:19
【问题描述】:

我非常需要的是一个数组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]);
    }
}

顺便说一句,我对指针不是很熟练。

【问题讨论】:

  • 无法复制,请提供minimal reproducible example
  • @mr.loop 您的代码运行良好。提供可编译的完整代码。
  • x = *y[1]; 是未定义的行为。您正在取消引用未初始化的指针。
  • @Jabberwocky 不好意思,我把问题搞砸了。最后进行编辑以使其精确且可重复。
  • @Lundin 已编辑以反映原始问题。

标签: arrays c pointers


【解决方案1】:

您的注释代码:

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]);
  }
}

【讨论】:

  • 你的答案是正确的。但是有没有办法使用指针数组而不是 int 数组来做到这一点。这是因为 B 的某些元素必须在某处存储索引和其他点。
  • @mr.loop 有办法做什么?这是XY Problem。您应该通过提出其他问题来告诉我们您实际上想要做什么。您的代码的问题是第二个数组中的指针不指向任何地方。
猜你喜欢
  • 2017-08-23
  • 1970-01-01
  • 2019-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 2021-02-07
相关资源
最近更新 更多