我需要的是一个数组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]);
}
}顺便说一句,我不太精通指南针。
发布于 2021-06-09 21:56:16
您的注释代码:
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
}访问指针所指向的东西称为取消引用指针。删除未初始化的指针会导致未定义的行为(google这个术语),很可能会出现seg错误。
我不知道你想要实现什么,但你可能想要这样的东西:
#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]);
}
}https://stackoverflow.com/questions/67899075
复制相似问题