I want it to print 100 200 300 My code is the following but it gives me an error when I run it, but not when Compiling the double pointer**p2 manages to print the first element notes[0] but when trying to print the following it gives an error, DEVc++ window the program stopped working
#include <stdio.h>
#include <stdlib.h>
/*Desplegar array entero usando puntero doble*/
int main()
{
int notas[3]={100,200,300};
int *p1=notas; /* Puntero a array*/
int **p2=&p1; /*puntero doble */
int i=0;
for(i=0;i<3;i++){
printf("%d ",**p2);
p2++;
}
//ME SALE ERROR AL EJECUTAR en DEV C++pero no al compilar
return 0;
}
When you define the double pointer
p2** = &p1
You are assigning the pointer p2 the memory address of p1.
In the loop, you increment p2, which will make it point to a different memory address. If you want to traverse the array, you must dereference p2 and increment the pointer it points to, which in this case would be p1.
If in the code you propose you change:
By:
You will increment the first level pointer and you will be able to traverse the array.
What you are doing is known as...
Pointer arithmetic.
The C language is strongly typed , which means that all data has a specific type that cannot be changed but can be converted. In the case of pointers, they will always be a pointer to something other than type pointer.
So, a pointer to integer (
int *
) and a pointer to character (char *
) are both pointers, but they are pointers to something different and therefore of a different type. This concept is vital to pointer arithmetic.Arithmetic operations such as addition (
+
) and subtraction (-
) 1 can be applied to a pointer , this will add to the value of the pointer (which is the memory address where the pointed data is located) the size of the pointed type, for example:In the above code ,
pc
andpi
initially point to address0x0
(null address) and at the end point to address0x1
and0x4
respectively despite having the same value added to both; this is becausechar
(type pointed topc
) takes up one byte of memory whileint
(type pointed topi
) takes four 2 .Your problem.
You are applying pointer arithmetic on the bad pointers. When you go forward
p2
(the pointer to pointer) you are going to the next pointer to pointer, not the next pointer to integer:You do not get an error when compiling because the operation you do is conceptually valid, but the program is wrong in its operation.
When advancing
p2
a position, it is possible that you are pointing to the position that contains200
or to the one that contains300
2 , which is interpreted as a pointer to dereference (**p2
) and since it is a memory address that does not correspond to your program: it causes a runtime failure. What you actually wanted to do is:1 Consequently also the
++
increment,--
decrement, autosum+=
and-=
autoresta;2 These values may change depending on the architecture .