I was training and studying the structures that are used in C, but when I was trying to create a data structure I got an issue, like that it was printing, random numbers. I think that he was printing the address of any array element in this pointer of array, but I want to know how do I fix it to make a print the value by a pointer pointing to an array.
#include <stdio.h>
#include <stdlib.h>
//creating a struct for a data structure
typedef struct {
int size;
int (*Arr)[10];
int top;
} Stack;
//function prototype
void print_Stack(Stack *pilha);
int main() {
Stack pilha;
int Elementos[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
pilha.Arr = &Elementos;
pilha.size = sizeof(Elementos) / sizeof(int);
print_Stack(&pilha);
return 0;
}
//creating a print stack function
void print_Stack(Stack *pilha) {
for (int x = 0; x < pilha->size; x++) {
printf("%d", pilha->Arr[x]);
}
}
I know that has a better way to create a array in struct, anyway, I want a solution for how I print the values in a pointer array to use it in another situations, if you explain it, it turns better :), because I am beginner in programming, and I like to learn it in hard way.
I was trying to make the get the address, put on variable, and the make the * again to get the value but it doesn’t work.
>Solution :
pilha->Arr is a pointer to an int[10] so you need to dereference it (with *) when printing the values in the array:
printf("%d", (*pilha->Arr)[x]);
// ^^^^^^^^^^^^^
Another option would be to make Arr an int* instead:
#include <stddef.h> // size_t
#include <stdio.h>
#include <stdlib.h>
#define ARRSIZE(x) (sizeof (x) / sizeof *(x))
typedef struct {
size_t size;
int *Arr; // int*
int top;
} Stack;
void print_Stack(Stack *pilha) {
for (size_t x = 0; x < pilha->size; x++) {
printf("%d", pilha->Arr[x]); // now this works
}
}
int main() {
Stack pilha;
int Elementos[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
pilha.Arr = Elementos; // and you assign it like this
pilha.size = ARRSIZE(Elementos);
print_Stack(&pilha);
return 0;
}