首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >元素指向另一个指针数组的指针数组。

元素指向另一个指针数组的指针数组。
EN

Stack Overflow用户
提问于 2021-06-09 06:59:19
回答 1查看 104关注 0票数 0

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

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

我知道,如果数组B[10]不是一个指针数组,而是整数数组,那么它会非常容易,但我需要这样做的另一个目的。

这就是我所做的,但也提供了分割错误。

代码语言:javascript
复制
#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]);
    }
}

顺便说一句,我不太精通指南针。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-09 21:56:16

您的注释代码:

代码语言:javascript
复制
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
    }
}

您的程序基本上等同于以下内容:

代码语言:javascript
复制
int main() {
    int *a;     // a is not initialized, it points nowhere
    *a = 1;     // probably you'll get a segfault here
}

访问指针所指向的东西称为取消引用指针。删除未初始化的指针会导致未定义的行为(google这个术语),很可能会出现seg错误。

我不知道你想要实现什么,但你可能想要这样的东西:

代码语言:javascript
复制
#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]);
  }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67899075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档