2

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. 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.

1
  • Hint: Check the types. Commented Nov 10, 2016 at 14:13

3 Answers 3

1

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. 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. 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);
Sign up to request clarification or add additional context in comments.

Comments

1
  • A pointer-to-pointer is not an array. Nor is it a pointer to a 2D array. 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;

  • You can't print a pointer using %d format specifier. You should use %p.

Corrected code for printing the address of the 2D array:

#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;
}

3 Comments

printf("%p\n", ipp); should not be printf("%p\n", (void*)ipp); ?
@Michi Yes indeed, if we are picky.
strictly speaking, printf("%p\n", ipp); should be printf("%p\n", (void *) ipp);
1

A pointer to pointer and a 2D array are not interchangeable, change to:

int (*ipp)[4]; /* A pointer to an array of 4 ints */
...
ipp = ventas;

1 Comment

It appears that the OP wants a pointer to a 2D array. Anyway, for the purpose of printing the address, a pointer to a 2D array or a pointer to the first element will give the same result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.