[C]Passage de tableau de structures ds 1 fctn

Résolu
Mumu -  
 Mumu -
Bonjour,

J'essaye en vain de créer une fonction qui travaille sur un tableau de structure.
On m'a expliqué qu'il était mieux de créer un tableau de pointeurs sur des structures, mais bien que je comprenne la chose, je n'arrive pas à la coder. En effet, je me retrouve avec quelque chose comme ça :

int loadDict(FILE *dictFile, struct symbolStruct** symbolList, int wordCount){
	short int i = 0;

	if ( (dictFile = fopen("dict", "r")) == NULL)
	{
		fprintf(stderr,"Dictionnary file can't be opened!\n");
		return 0;
	} 
	
	symbolList = malloc(wordCount*sizeof(struct symbolStruct*));
	for ( i = 0; i < wordCount; i++){
		symbolList[i] = malloc(sizeof(struct symbolStruct));}


	dictFile = fopen("dict", "r");*/

	symbolList = malloc(wordCount*sizeof(struct symbolStruct*));
	for ( i = 0; i < wordCount; i++)
		symbolList[i] = malloc(sizeof(struct symbolStruct));
..
}

int main(int argc, char* argv[]){
	
	FILE* dictDescriptor;
	int wordCount;
	struct symbolStruct** symbolList;

	loadDict(dictDescriptor, symbolList);

..
}


Ca compile moyennement bien, surtout au niveau des mallocs (j'ai du mal à cerner ce que je fais avec un malloc, surtout dans la fonction), les structures que j'affecte sont utilisables à l'intérieur de la fonction, mais dès que j'en sors, c'est fini...

Merci d'avance, je planche dessus depuis quelque temps déjà :(
Configuration: Linux
Firefox 2.0.0.8

11 réponses

  1. Mumu
     
    Je me suis trompé dans le quote, il n'y a évidemment qu'une seule allocation :

    int loadDict(FILE *dictFile, struct symbolStruct** symbolList, int
    wordCount){
    	short int i = 0;
    
    	if ( (dictFile = fopen("dict", "r")) == NULL)
    	{
    		fprintf(stderr,"Dictionnary file can't be opened!\n");
    		return 0;
    	} 
    	
    	symbolList = malloc(wordCount*sizeof(struct symbolStruct*));
    	for ( i = 0; i < wordCount; i++){
    		symbolList[i] = malloc(sizeof(struct symbolStruct));}
    ..
    }
    
    int main(int argc, char* argv[]){
    	
    	FILE* dictDescriptor;
    	int wordCount;
    	struct symbolStruct** symbolList;
    
    	loadDict(dictDescriptor, symbolList);
    
    ..
    }
    0
  2. mype Messages postés 2459 Date d'inscription   Statut Membre Dernière intervention   437
     
    tu as oublié de faire le cast pour le malloc c'est surement pour ça que tu as des erreur a ce niveau

    essaye ça
    symbolList = (struct symbolStruct **) malloc(wordCount*sizeof(struct symbolStruct*));

    et
    symbolList[i] = (struct symbolStruct *) malloc(sizeof(struct symbolStruct));
    0
  3. Mumu
     
    Merci de te pencher sur mon problème !

    Avec ta solution, cela compile bien, et le malloc ne génère pas d'erreur. Cependant j'ai un segmentation fault lorsque j'essaye d'affecter les structures, par exemple :

    (*symbolList[i]).firstPx = 2;
    0
  4. mype Messages postés 2459 Date d'inscription   Statut Membre Dernière intervention   437
     
    en general c'est un debordement de memoire tu es sure d'avoir alloué assez de memoire ?
    0
  5. Vous n’avez pas trouvé la réponse que vous recherchez ?

    Posez votre question
  6. Mumu
     
    Ca plante à la toute première affectation, pour i=0 :(
    Soit je ne fais pas l'allocation avec malloc de la bonne façon, soit je n'affecte pas de la bonne façon... ?
    0
  7. mype Messages postés 2459 Date d'inscription   Statut Membre Dernière intervention   437
     
    essaye sans le "*"
    (symbolList[i]).firstPx = 2;
    0
  8. Mumu
     
    request for member ‘firstPx’ in something not a structure or union..

    Il est pas venu le jour où les pointeurs seront clairs pour moi :/
    0
  9. mype Messages postés 2459 Date d'inscription   Statut Membre Dernière intervention   437
     
    c'est peu etre une question bete mais as tu placer l'affectation au bon endroit ?

    for ( i = 0; i < wordCount; i++){
    		symbolList[i] = malloc(sizeof(struct symbolStruct));
                    (symbolList[i]).firstPx = 2;}
    0
    1. Mumu
       
      C'était peut-être bête mais c'était mon erreur à peu de chose près...
      Je faisais d'abord une bouche pour allouer puis une seconde pour affecter et j'avais oublié de réinitialiser i à 0.. Je m'excuse :)

      Ceci dit j'ai toujours un problème : à l'intérieur de la fonction où je fais l'allocation et l'affectation tout se passe bien, mais une fois sorti de celle-ci j'ai bien un segmentation fault
      0
  10. lami20j Messages postés 21506 Date d'inscription   Statut Modérateur, Contributeur sécurité Dernière intervention   3 571
     
    Salut,

    (*symbolList[i]).firstPx = 2;
    c'est plutôt comme ça mais je préfère les flèches.

    regarde cet exemple
    lami20j@debian:~/trash$ cat ccm.c
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
      struct symbolStruct {
              int firstPx;
              int firstPy;
      };
    
      struct symbolStruct** symbolList;
    
      symbolList = (struct symbolStruct**) malloc (sizeof(struct symbolStruct*));
      symbolList[0] = (struct symbolStruct*) malloc (sizeof(struct symbolStruct));
    
      (*symbolList[0]).firstPx = 2;
      symbolList[0]->firstPy = 20;
    
      printf("firstPx = %d\n",symbolList[0]->firstPx);
      printf("firstPy = %d\n",symbolList[0]->firstPy);
    
      symbolList = (struct symbolStruct**) malloc (sizeof(struct symbolStruct*));
      symbolList[1] = (struct symbolStruct*) malloc (sizeof(struct symbolStruct));
    
      (*symbolList[1]).firstPx = 5;
      symbolList[1]->firstPy = 50;
    
      printf("firstPx = %d\n",symbolList[1]->firstPx);
      printf("firstPy = %d\n",symbolList[1]->firstPy);
    
      return 0;
    }
    lami20j@debian:~/trash$ gcc ccm.c
    lami20j@debian:~/trash$ ./a.out
    firstPx = 2
    firstPy = 20
    firstPx = 5
    firstPy = 50
    
    0
    1. Mumu
       
      Du coup c'est exactement ce que je fais, mais dans une fonction qui prend comme paramètre struct symbolStruct** symbolList.

      Mon problème est que j'appelle cette fonction dans le main, qu'à l'intérieur de celle-ci les structures sont bien initialisées, mais que si je fais, par exemple
      		printf("%d %d %d %d %c\n", symbolList[0]->firstPx, symbolList[0]->secondPx, symbolList[0]->thirdPx, symbolList[0]->fourthPx, symbolList[0]->symbol);

      Les valeurs affichées sont erronées !?

      Si je reprends ton exemple, voilà ce que j'essaye de faire :
      #include <stdio.h>
      #include <stdlib.h>
      
      struct symbolStruct {
                int firstPx;
                int firstPy;
      };
      
      int load(struct symbolStruct** symbolList)
      {
      
      
        symbolList = (struct symbolStruct**) malloc (sizeof(struct symbolStruct*));
        symbolList[0] = (struct symbolStruct*) malloc (sizeof(struct symbolStruct));
      
        symbolList[0]->firstPx = 2;
        symbolList[0]->firstPy = 20;
      
        printf("firstPx = %d\n",symbolList[0]->firstPx);
        printf("firstPy = %d\n",symbolList[0]->firstPy);
      
        symbolList = (struct symbolStruct**) malloc (sizeof(struct symbolStruct*));
        symbolList[1] = (struct symbolStruct*) malloc (sizeof(struct symbolStruct));
      
        symbolList[1]->firstPx = 5;
        symbolList[1]->firstPy = 50;
      
        printf("firstPx = %d\n",symbolList[1]->firstPx);
        printf("firstPy = %d\n",symbolList[1]->firstPy);
      
        return 0;
      }
      
      int main(void)
      {
      	struct symbolStruct** symbolList;
      	load(symbolList);
        	printf("firstPx = %d\n",symbolList[1]->firstPx);
        	printf("firstPy = %d\n",symbolList[1]->firstPy);
      	return 0;
      }


      Et bien entendu c'est aux printf du main que cela plante (seg fault).
      0
  11. lami20j Messages postés 21506 Date d'inscription   Statut Modérateur, Contributeur sécurité Dernière intervention   3 571
     
    c'est normal puisque ta fonction retourne un entier mais tu as besoin qu'elle retourne un pointeur sur la structure

    lami20j@debian:~/trash$ cat ccm.c
    #include <stdio.h>
    #include <stdlib.h>
    
    struct symbolStruct {
              int firstPx;
              int firstPy;
    };
    
    struct symbolStruct ** load(struct symbolStruct** symbolList)
    {
    
    
      symbolList = (struct symbolStruct**) malloc (sizeof(struct symbolStruct*));
      symbolList[0] = (struct symbolStruct*) malloc (sizeof(struct symbolStruct));
    
      symbolList[0]->firstPx = 2;
      symbolList[0]->firstPy = 20;
    
      printf("firstPx = %d\n",symbolList[0]->firstPx);
      printf("firstPy = %d\n",symbolList[0]->firstPy);
    
      symbolList = (struct symbolStruct**) malloc (sizeof(struct symbolStruct*));
      symbolList[1] = (struct symbolStruct*) malloc (sizeof(struct symbolStruct));
    
      symbolList[1]->firstPx = 5;
      symbolList[1]->firstPy = 50;
    
      printf("firstPx = %d\n",symbolList[1]->firstPx);
      printf("firstPy = %d\n",symbolList[1]->firstPy);
    
      return symbolList;
    }
    
    int main(void)
    {
            struct symbolStruct** symbolList;
            symbolList = load(symbolList);
    
            printf("Dans main\n");
    
            printf("firstPx = %d\n",symbolList[1]->firstPx);
            printf("firstPy = %d\n",symbolList[1]->firstPy);
            return 0;
    }
    lami20j@debian:~/trash$ gcc ccm.c
    lami20j@debian:~/trash$ ./a.out
    firstPx = 2
    firstPy = 20
    firstPx = 5
    firstPy = 50
    Dans main
    firstPx = 5
    firstPy = 50
    
    
    0
  12. Mumu
     
    Aaaah d'accord !
    Ca m'embête un peu car le retour d'entier j'en avais besoin mais j'ai divisé la fonction en 2 du coup.
    Ben tout fonctionne correctement, merci beaucoup mype et lami20j pour vos lumières ;)
    0