简体   繁体   English

C-指向数组的分段错误

[英]C - Segmentation fault with pointer to array

i'm hoping someone can help me with this little piece of code. 我希望有人可以用这小段代码来帮助我。 It's a stupid test, but i dont know what is it that i am doing wrong. 这是一个愚蠢的测试,但是我不知道我做错了什么。 It's like this: 就像这样:

#include <stdio.h>

int **ipp;

int ventas [3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

int main(void){

    ipp = (int **)ventas;

    printf("%d\n", **ipp);

    return 0;
}

It compiles (I'm using GCC), but when I execute it I keep getting a segmentation fault. 它可以编译(我正在使用GCC),但是当我执行它时,我总是遇到分段错误。 What am I doing wrong? 我究竟做错了什么? I think it has something to do with an un-initalized pointer, but 'ventas' is an array so it is already initialized, and it's assigned to **ipp. 我认为它与未初始化的指针有关,但是'ventas'是一个数组,因此它已被初始化,并且已分配给** ipp。

A pointer to pointer and a 2D array are not interchangeable, change to: 指针和2D数组的指针不可互换,请更改为:

int (*ipp)[4]; /* A pointer to an array of 4 ints */
...
ipp = ventas;
  • A pointer-to-pointer is not an array. 指向指针的指针不是数组。 Nor is it a pointer to a 2D array. 它也不是指向2D数组的指针。 They aren't the slightest compatible. 它们一点也不兼容。 Just forget about pointer-to-pointers in this case. 在这种情况下,只需忽略指针对指针即可。

  • If you want a pointer to a 2D array, you must write int (*ipp)[3][4] = &ventas; 如果要指向2D数组的指针,则必须编写int (*ipp)[3][4] = &ventas;

  • You can't print a pointer using %d format specifier. 您不能使用%d格式说明符打印指针。 You should use %p . 您应该使用%p

Corrected code for printing the address of the 2D array: 更正了用于打印2D数组地址的代码:

#include <stdio.h>

int main(void){
  int ventas [3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
  int (*ipp)[3][4];

  ipp = &ventas;
  printf("%p\n", ipp);

  return 0;
}

When you have such casting like 当你有这样的演员

ipp = (int **)ventas;

then the value of the variable is the address of the first element of the array ventas . 那么变量的值就是数组ventas的第一个元素的地址。 In this case after dereferencing the pointer 在这种情况下,取消引用指针后

*ipp

you get the value stored at this address. 您将获得存储在该地址的值。 If to assume that sizeof( int ) is equal to sizeof( int * ) than the first element of the array equal to 1 is considered as a memory address. 如果假设sizeof( int )等于sizeof( int * ) ,则将数组的第一个元素等于1视为内存地址。 After applying second dereferencing 应用第二次解引用后

**ipp

you get memory access violation. 您收到内存访问冲突。

It will be correct to write either like 像这样写是正确的

int ( *ipp )[4] = ventas;

and then 接着

printf("%d\n", **ipp);

or like 或喜欢

int *ipp = ( int * )ventas;

and then 接着

printf("%d\n", *ipp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM