Problems in a string array of a structure

Asked

Viewed 40 times

0

I’m having a problem with an array of strings I’m trying to access from a structure. The structure is placed in a header.h which has the following format :

typedef struct {

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

In my main.c , made a function that puts in the string array char *produtos[200000]; the count of a file line by line. That is 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 samples the last line of the file from where I am copying line to line for the array. When I invoke the array in another function the content that is present in the array is junk , which leaves me with the idea that the array is not global.

How do I get the array to receive what it’s supposed to and access it in a global way?

PS: The file I am accessing line by line to place in the array has the following format :

AF1184
AF1198
FD1083
DV1293
DV1294
...

the function aplica is thus defined :

char *aplica (char *str) {

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

   return tokenPtr;
 }

1 answer

1


When you use

char *produtos[200000];

you have an array of (200000) pointers.

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

  • Yes! That’s it! I was looking for the reason why I was failing and agr @pmg already works. Thanks PS: This array works globally ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.