Aide pour code C

Résolu
tarkos01 Messages postés 10 Date d'inscription lundi 4 octobre 2004 Statut Membre Dernière intervention 17 novembre 2008 - 2 juil. 2007 à 09:01
BruNews Messages postés 21040 Date d'inscription jeudi 23 janvier 2003 Statut Modérateur Dernière intervention 21 août 2019 - 2 juil. 2007 à 10:00
je voudrais  comprendre les pointeurs et les chaines, j'ai commencé a taper un morceaux de code en C mais il y a un probleme. je ne vois pas lequel malheureusement.

#include<stdio.h>
#include<stdlib.h>
#include <string.h>

/* fonction d'un pointeur*/

int main (void) {
  int x = 100;
  int * y;
  char * text, * ini;
  ini = text;  if ((text (char *)  malloc(x * sizeof * text)) NULL)
    fprintf(stderr, "\n\n echec allocation \n\n");
 
  y = &x;
 
  printf("\nacces direct a la valeur de X: \t%d\n", x);
  printf("\nacces indirect a la valeur de X: \t%d\n", *y);
  printf("\nacces direct a l'adresse de X: \t%d\n", &x);
  printf("\nacces indirect a l'adresse de X: \t%d\n", y);
  printf("\nacces direct a l'adresse de Y: \t%d\n", &y);
 
  puts("\nentrez un text de 99 lettres\n");
  while (x-- && (*text = getchar()) != '\n')
    text++;
 
  printf("\n%s\n", *ini);
 
 
  free(text);
 
  return 0;
 
}

1 réponse

BruNews Messages postés 21040 Date d'inscription jeudi 23 janvier 2003 Statut Modérateur Dernière intervention 21 août 2019
2 juil. 2007 à 10:00
if((text = (char*)  malloc(x * sizeof * text)) == NULL)
en clair c'est:
sizeof d'un pointeur est 4 sur system 32 bitsif((text (char*)  malloc(100*4)) NULL)




char *text, *ini;
ini = text; // ini POINTERA ON NE SAIT OUif((text (char*)  malloc(400)) NULL)
...


free(text); // NON !!!
tu as déplacé le pointeur text, il faut faire free sur sa sauvegarde ini.


char *text, *ini;if((text (char*)  malloc(100*4)) NULL) return 0;
ini = text;
...
...
free(ini);

ciao...
BruNews, MVP VC++
3
Rejoignez-nous