Problems in an array of strings in a structure

0

I'm having a problem about an array of strings that I'm trying to access from a structure. The structure is set to header.h which has the following format:

typedef struct {

 char *produtos[200000];
 int contador;
} Produtos,*ProdutosP;

In my main.c , I made a function that places in the array of strings char *produtos[200000]; the counting of a file line by line. Here's the function:

int lerProdutos (FILE *fd )   {

char buff [64];
p->contador = 0;
if (fd == NULL)
    return 1;

  while (fgets (buff,64,fd) != NULL )
  { 
    p->produtos[p->contador] = aplica (buff);         
    p->contador++;
  } 
  return p->contador;
}

When I try to access position 1, 2, 3 .. the array just shows the last line of the file where I am copying line by line to the array. When I invoke the array in another function the content that is present in the array is garbage, which leaves me with the idea that the array is not global.

How do I get the array to receive what it is supposed to give you to access it in a global way?

PS: The file I'm accessing line by line to put into the array has the following format:

AF1184
AF1198
FD1083
DV1293
DV1294
...

the aplica function is thus defined:

char *aplica (char *str) {

  char *tokenPtr;
  tokenPtr = strtok(str, "\n \t");

   return tokenPtr;
 }
    
asked by anonymous 12.03.2016 / 17:02

1 answer

1

When you use

char *produtos[200000];

You have an array of (200000) pointers.

With your code all these pointers point to the result of the aplica() function.
What you need to do is assign a different value to each pointer (possibly preceded by malloc() and strcpy() ).

    
12.03.2016 / 17:18