# Thread: Passing an array of structures dynamically!

1. ## Passing an array of structures dynamically!

Hi, as you can see, I'm really don't know what's the best way to do this...

This is an example of what I'm trying to do:

struct NAME{

//Fields...

}

int main()
{
struct NAME *pointer;

(give the pointer a size with malloc);

function(pointer);
}

void function(struct NAME *pointer)
{

now here is where I get confused, do I have to do malloc again (pass the size of the pointer to function)? Or theres no need?
}

2. No, a pointer simply contains the address of some allocated memory. So you pass a pointer to some function so that function has the address to your allocated memory.
Think of a pointer as a note or something that contains the address to your actual object or memory.

3. Ok, I think I get your point.

But I still got a problem a bit related to this... This is the logic of my 'program' (very simple):

I have declared a pointer to a structure in main.

struct LINEA *lista;

I pass it to a function like this:

llegirlineasTxt(lista);

Now in my function, I give the pointer the size with malloc, and then scan a file to put to the fields of the structures some values:

while(!feof(lineasTxt))
{
fscanf(lineasTxt,"&#37;c" ,&lista[numLinia].identificador);
fscanf(lineasTxt, "%s", &lista[numLinia].nombre);
fscanf(lineasTxt, "%d",&lista[numLinia].valor);
getc(lineasTxt);
numLinia++;

All ok at this point

And if I print some results (just to test it) like this:

int i;
for(i = 0; i<7; i++)
printf("%c\n", lista[i].identificador);

for(i = 0; i<7; i++)
printf("%d\n", lista[i].valor);

If I put this inside that function, it prints the results correctly.. now if I instead put this piece of code in main (right after calling the function). I get a 'bus error' , or I get some weird values...

Anyone knows what's the matter?

4. Post the code. Also read the FAQ on using feof as the loop condition (it's bad).

Popular pages Recent additions