Recently was handling with this exercise:
Count the size of each element in an array. Create a function
my_count_on_it
, which receives a string array as a parameter and returns an array with the length of each string.
Structures:
typedef struct s_string_array {
int size;
char **array;
} string_array;
typedef struct s_integer_array {
int size;
int *array;
} integer_array;
So the right answer was:
#include <string.h>
integer_array *my_count_on_it(string_array *a) {
integer_array *ptr;
ptr = (integer_array *)malloc(sizeof(integer_array));
ptr->size = a->size;
ptr->array = (int*)malloc(ptr->size * sizeof(int));
for (int i = 0; i < a->size; i++) {
ptr->array[i] = strlen(a->array[I]);
}
return ptr;
}
I know that pointer stores address of some variable, but I can't understand why in this case I can't create a variable type of integer_array
and do all operations(in the loop) with it, and only then store its address in integer_array * ptr
? and one more question, if so why we are creating a pointer sizeof(integer_array)
?
For instance:
int variable = 5;
int *ptr = &variable;
In this simple case, I create variable and pointer separately and store the address. The confusing thing in the first code is it seems to me like we are creating only a pointer, which is not pointing to some address.