Doing some training code with arrays i run into the following issue: If i ask the user how long the array is supposed to be, malloc it and then ask for the values inside the array and return the list to main and assing it to a pointer to list of integers:
#include <stdio.h>
#include <stdlib.h>
int *make_list(void);
void get_num(int *);
void print_reverse(int *, int);
int main(void)
{
int *v = NULL;
v = make_list();
return 0;
}
int *make_list(void)
{
int n = 0;
int i = 0;
int *tmp = NULL;
printf("how long? ");
get_num(&n);
tmp = (int *) malloc(n * sizeof(int));
for (i = 0; i < n; i++) {
printf("value ");
get_num(tmp+i);
}
return tmp;
}
void get_num(int *n)
{
char buf[BUFSIZ];
printf("number: ");
fgets(buf, sizeof(buf), stdin);
*n = atoi(buf);
}
i lost all ways to find out how much elements that list has, right?
And the other way around: If i have a list of integers and add it as an argument to a fucntion:
print_list(v)
there is no way to find out how long the list is inside the function called print_list() ?
If both is true, would using a global variable for the length be a good solution?
Yes, you have to keep a variable wich keeps number of elements in your array.
In many situations I find it convenient to hold ptr to array and counter together in one simple structure. If element of an array is a struct itself then I add another int to my structure to hold sizeof of one element. This way you can have a lib function to init an array, to add an element to it etc...
Q.2: Inside of the function make_list() i declare a struct num_list tmp, but i don't allocate any memory. I allocate memory to the list, depending how much elements it will contain. Will the struct num_list tmp have enough memory to store the list, no matter how much elements the list contains? (The question reveals that memory allocation is not always clear to me).
Your Q.2 is now clear - yes, the tmp structure has a pointer *v which will hold address of the beginning of the array of integers, which you malloc'ed. Corona clarified it already.