I have the following assumptions about the pointers. They can be interpreted as arrays as long as they are initialized to occupy the memory spaces required for "an array". I would like to understand a little more about how pointers improve the dynamics of a C program.
Here is a program that I think shows this transformation from a pointer to an array and how - a one-dimensional array is a constant pointer, a two-dimensional array will be a pointer to a constant pointer (type **). How could I print the array we have made, with a single for loop and using pointers?
/* matriz de n filas y cada fila de un número variable de elementos */
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **p;
int n, m, i;
do {
printf("\n Numero de filas: "); scanf("%d", &n);
}while(n <= 0);
p = (int**) malloc(n*sizeof(int*));
for(i = 0; i < n; i++)
{
int j;
printf("Número de elementos de fila %d: ", i+1);
scanf("%d", &m);
p[i] = (int*)malloc(m*sizeof(int));
for(j = 0; j < m; j++)
{
printf("Valor del elemento p[%d][%d]: ", i+1, j+1);
scanf("%d", &p[i][j]);
}
}
// printf("%d", **p ); //Aqui va nuestra impresión de matriz
return 0;
}
As soon as I have time maybe I can post the answer. Thanks.
-----------------------------EDITION-------------------- ----------
Regarding the responses and comments I have received. I give an example where I illustrate a little more thoroughly my point of view. And also, show how memory can be freed, something I said to the air as a comment, not an assertion within my program.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
float *pf = NULL;
int num, i;
do{
printf("Número de elementos del vector: ");
scanf("%d", &num);
}while(num < 1);
/* Asigna memoria: num*tamaño bytes */
pf = (float *) calloc(num, sizeof(float));
if(pf == NULL)
{
puts("Error en la asignación de memoria.");
return 1;
}
printf("Introduce %d valores \n", num);
for(i = 0; i < num; i++)
{
printf("Valor del elemento %i: ", i);
scanf("%f", &pf[i]);
/* proceso del vector */
}
for(i = 0; i < num; i++){
printf("pf[%i]: %f\n", i+1, pf[i]); printf("\tTamaño de pf[%i]: %d\n", i+1, sizeof(pf[i]));}
for(i = 0; i < num; i++){
printf("pf[%i]: %f\n", i+1,*pf); printf("\tTamaño de pf[%i]: %d\n", i+1, sizeof(*pf)); *pf++;}
/* liberación de la memoria ocupada */
free(pf);
for(i = 0; i < num; i++){
printf("pf[%i]: %f\n", i+1,*pf); printf("\tTamaño de pf[%i]: %d\n", i+1, sizeof(*pf)); *pf++;}
for(i = 0; i < num; i++){
printf("pf[%i]: %f\n", i+1, pf[i]); printf("\tTamaño de pf[%i]: %d\n", i+1, sizeof(pf[i]));}
return 0;
}
EXECUTION
N├║mero de elementos del vector: 2
Introduce 2 valores
Valor del elemento 0: 2
Valor del elemento 1: 2
pf[1]: 2.000000
Tamaño de pf[1]: 4
pf[2]: 2.000000
Tamaño de pf[2]: 4
pf[1]: 2.000000
Tamaño de pf[1]: 4
pf[2]: 2.000000
Tamaño de pf[2]: 4
pf[1]: 0.000000
Tamaño de pf[1]: 4
pf[2]: 0.000000
Tamaño de pf[2]: 4
pf[1]: 0.000000
Tamaño de pf[1]: 4
pf[2]: 0.000000
Tamaño de pf[2]: 4
Thanks for the valuable feedback. Especially PaperBirdMaster . Now it's a little clearer.
This is not entirely false, but it is not true either. The concept you're describing 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, an integer pointer (
int *
) and a double-precision number pointer (double *
) 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 data pointed to) is the size of the type pointed to, for example:In the code above ,
pc
andpi
initially point to the address0x0
(null address) and at the end point to the address0x1
and0x4
respectively despite the fact that both have been added the same value; this is becausechar
(pointed to typepc
) occupies one byte of memory whileint
(pointed to typepi
) occupies four 2 .The indexing operator (the brackets
[]
), is a syntactic sugar of pointer arithmetic, the expressionp[10]
beingp
a pointer, is equivalent to*(p + 10)
3 as indicated in the standard (my translation):So, answering your question, pointers can always be interpreted as arrays 4 , just apply arithmetic on them, but the behavior will be undefined if a pointer is treated as an array that is not as the standard says (my translation ):
A pointer that points to a variable is conceptually an array of an element, and since a pointer can point to various data throughout its life, it can be used interchangeably to point to variables and to point to arrays, so interchangeably a pointer may or may not be interpreted as an array:
You can't, from what I see in your code you are not generating a two-dimensional array but a sawtooth array . Sawtooth matrices are those in which each row of the matrix has a variable number of columns.
You could print the matrix with a single loop
for
if the number of columns in each row were fixed:Other things to keep in mind.
p
,n
,m
,i
andj
do not provide any information about the mission of those variables, at a glance we cannot know what they mean or why they are necessary.Following the tips above, your code could look something like:
++
increment,--
decrement, autosum+=
and-=
autosubtract;p[10]
and10[p]
are equivalent, absurd as it may seem.There seems to be no other way to print this result than the canonical form of multiple for loops, which don't use a single pointer. To do this, the pointer needs to know the position of each of the addresses.
EXECUTION