undesirable character displayed when executing [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have some troubles when executing my program, some characters appeared out of nowhere ( especially this one : and sometimes others) , I don't understand where is the problem and how to delet them.
Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <magic.h>
#include <string.h>
typedef struct Chaine
{
char * Lachaine;
int Taille_C;
} Chaine ;
char * test ( char*);
void ReccuperationTexte(char** txt);
void afficheTable2D(int** Table, Chaine * Tab_du_texte );
int * Tab_fin( int** Table, Chaine * Tab_du_texte );
char*Le_suff(int* tab_suf,Chaine *);
int ** Table2D ( Chaine *);
char* copietext ( char * , int );
int taille_texte ( char * fichier);
int main (void)
{
system("ls");
Chaine *Tab_du_texte=NULL;
Tab_du_texte=(Chaine*)malloc(sizeof(Chaine));
Tab_du_texte->Lachaine=NULL;
Tab_du_texte->Taille_C=0;
char fichier[50];
char * restest=NULL;
char * LeSuffixe=NULL;
LeSuffixe=(char*)malloc(sizeof(char)*50);
restest=(char*)malloc(sizeof(char)*15);
int **Table=NULL;
int* Tab_final=NULL;
int i;
Tab_final=(int*) malloc (sizeof(int)*100);
printf("tapez le nom du fichier s'il vous plais: ");
scanf(" %s",fichier);
restest=test(fichier);
while(strcmp( restest, "ASCII text") != 0 || strcmp( restest, "rien")==0)
{
printf("il ne s'agit pas d'un fichier texte ou bien le fichier n'existe pas.\nVeillez choisir un autre:");
scanf(" %s",fichier);
restest=test(fichier);
}
printf("vous avez bien selectionné un fichier texte.\n");
Tab_du_texte->Taille_C= taille_texte (fichier);
/*copie du fichier texte dans un tab dynamique*/
Tab_du_texte->Lachaine=(char*)malloc(sizeof(char)*Tab_du_texte->Taille_C);
Tab_du_texte->Lachaine= copietext (fichier, Tab_du_texte->Taille_C);
printf("La chaine est: %s",Tab_du_texte->Lachaine);
fflush(stdin);
/*creation du tableau 2D */
Table=Table2D(Tab_du_texte);
afficheTable2D(Table,Tab_du_texte);
Tab_final=Tab_fin(Table,Tab_du_texte);
for(i=0;i<Tab_du_texte->Taille_C;i++)
printf("%d",Tab_final[i]);
LeSuffixe=Le_suff(Tab_final,Tab_du_texte);
printf("Le suff est:%s",LeSuffixe);
for(i=0; i<Tab_du_texte->Taille_C; i++)
{
free(Table[i]);
}
free(Table);
free(restest);
return 0;
}
char * test ( char* ftest)
{
magic_t cookie;
const char *description;
char *res;
res=(char*)malloc(sizeof(char)*15);
cookie = magic_open(MAGIC_NONE);
if (cookie != NULL)
{
/* on va charger la base de données */
if (magic_load(cookie, NULL) == 0)
{
description = magic_file(cookie, ftest);
if (description != NULL && strlen(description)<15)
strcpy(res,description);
else
{
res="rien";
}
magic_close(cookie);
}
else
fprintf(stderr, "error loading the magic database\n");
}
return res;
}
int taille_texte ( char * fichier)
{
Chaine *Tab_Texte=NULL;
Tab_Texte=(Chaine*)malloc(sizeof(Chaine));
FILE* Texte= NULL;
Texte = fopen(fichier, "r");
fseek(Texte, 0, SEEK_END);
Tab_Texte->Taille_C=ftell(Texte);
return Tab_Texte->Taille_C;
}
char * copietext ( char * fichier, int taille_C)
{
char *Tab_Texte=NULL;
FILE* Texte= NULL;
Texte = fopen(fichier, "r");
fseek(Texte, 0, SEEK_SET);
Tab_Texte=(char*)malloc(sizeof(char)*taille_C);
fread(Tab_Texte,sizeof(char)*(taille_C),1,Texte);
return Tab_Texte;
}
int ** Table2D ( Chaine * Tab_du_texte)
{
int i,j,k,t;
int** Table=NULL;
t=Tab_du_texte->Taille_C;
Table=(int**)malloc(sizeof(int*)*t);
for(j=0;j<t;j++)
Table[j]=(int*)malloc(sizeof(int)*t);
for(j=0; j<t; j++) // Initialisation de la première ligne des i
{
Table[0][j]=0;
}
for(i=1; i<t ;i++)
{
for(k=0; k<i; k++)
{
Table[i][k]=0;
}
for(j=i; j<t; j++)
{
if(((Tab_du_texte->Lachaine[i]>=32 && Tab_du_texte->Lachaine[i]<=126) && (Tab_du_texte->Lachaine[j]>=32 && Tab_du_texte->Lachaine[j]<=126)) && Tab_du_texte->Lachaine[i-1]==Tab_du_texte->Lachaine[j])
{
Table[i][j]=Table[i-1][j-1]+1;
}
else
{
Table[i][j]=0;
}
}
}
return Table;
}
void afficheTable2D(int** Table, Chaine * Tab_du_texte)
{
int i, j,t;
t=Tab_du_texte->Taille_C;
for(i=0; i<t; i++)
{
for(j=0; j<t; j++)
{
if(i>j)
printf(" ");
else
printf("%d",Table[i][j]);
}
printf("\n");
}
printf("\n");
}
int * Tab_fin(int** Table,Chaine * Tab_du_texte)
{
int i,j,t;
t=Tab_du_texte->Taille_C;
int max =0;
int * Tab_suff=NULL;
Tab_suff=(int*)malloc(sizeof(int)*t);
Tab_suff[0]=0;
for (j=0;j<t;j++)
{
for(i=0;i<=j;i++)
{
if (Table[i][j]>max)
max= Table[i][j];
}
Tab_suff[j]=max;
max=0;
}
return Tab_suff;
}
char*Le_suff(int* tab_suf,Chaine * Tab_du_texte)
{
int max,i,max_i,t;
char* suffixe=NULL;
t=Tab_du_texte->Taille_C;
max=0;
for(i=0;i<t;i++)
{
if(max<tab_suf[i])
{
max=tab_suf[i];
}
}
for(i=0;i<t;i++)
{
if(max==tab_suf[i])
max_i=i;
}
suffixe=(char*)malloc(sizeof(char)*max);
strncpy(suffixe,&Tab_du_texte->Lachaine[max_i-(max-1)],max);
printf("\n%s\n",suffixe);
return suffixe;
}
Sorry, the code is not well identified but I will fix it later. ( the program is in french )

Pretty difficult to read french c-code.... Anyway, I would take a second look at the fread in copietext. I don't think that will give you a zero-terminated string.

Related

C error: linker command failed with exit code 1 (use -v to see invocation)

I'm new to C, I've already searched and I haven't found an answer, but I've been trying to get the program to give me a list with the name of the products typed in by the user followed by the sum of all prices and I've found the error:
clang-7 -pthread -lm -o main main.c
/tmp/main-7440c0.o: In function `main':
main.c:(.text+0x12b): undefined reference to 'N'
main.c:(.text+0x164): undefined reference to 'Digitanome'
main.c:(.text+0x17f): undefined reference to 'Lista'
clang-7: error: linker command failed with exit code 1 (use -v to see invocation)
exit status 1
The code I've been trying is this one:
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
extern char (N[][40]);
int i;
char p;
int cod,cont, soma2;
char soma[100];
int Digitanome( char [][40], int );
void Lista( char [100][40], int );
typedef struct {
char produto[30];
char seçao [30];
float preco;
int cargo;
}Supermercado;
Supermercado compra;
int main(void)
{
char Nome[100][40] = { '\0' };
int qtdNomes = 0;
soma2 = 0;
do{
printf("\n\nEm qual seção está seu produto?");
printf("\n1-Frutas \n2-Doces \n3-Material de Limpeza\n --> ");
scanf("%d",&cod);
if(cod == 1){
*compra.seçao = *strcpy(compra.seçao,"Frutas");
}
if(cod == 2){
*compra.seçao = *strcpy(compra.seçao, "Doces");
}
if(cod == 3){
*compra.seçao = *strcpy(compra.seçao,"Material de Limpeza");
}
int Digitanome(char N[][40], int i);
{
printf("Informe o produto que você quer nesta seção: \n");
scanf("%s", & *N[i]);
*compra.produto = Digitanome( Nome, qtdNomes );
Lista( Nome, qtdNomes );
return ++i;
}
return 0;
printf("Informe o preço do produto: \n");
scanf("%f", &compra.preco);
soma2 = soma2 + compra.preco;
printf("\nDeseja mais algum produto? \n4-Sim \n0-Não, sair \n --> ");
scanf("%d",&cont);
}while(cont == 4);
{
if (cont == 0)
printf("\nFIM DAS COMPRAS!\n");
void Lista(char p[100][40], int i);{
int j = 0;
for (; j < i; j++ )
printf("\nSeus produtos são:%s\n", compra.produto);
}
printf("Essa compra está custando: %i \n", soma2);
}
}
Can anyone explain to me what is happening and how to solve it?
Several problems:
extern char (N[][40]);
You declare N as extern without initialization so you would also need to delcare it in another module with initialization. But you don't actually ever use the variable N. You have N[][40] as an argument to Digitanome. Once you fix item numbers 2 and 3 below, you can remove extern char (N[][40]); completely.
You define Digitanome and Lista inside main(). You need to define them outside of main().
You have semicolons at the end of Digitanome and Lista function definitions. You need to remove those.
You have code following the return 0 statement.
You call Digitanome from inside Digitanome. That is probably not what you want.
Once you fix those problems, you will probably find more.
As Jim mentioned, there is some syntax error in your code you need to fix.
I could not understand the logic of your code so if you still need help, comment to me so that we can do it together!
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
extern char (N[][40]); int i; char p; int cod,cont, soma2; char soma[100];
int Digitanome( char [][40], int ); void Lista( char [100][40], int ); int qtdNomes = 0;
char Nome[100][40] = { '\0' };
typedef struct { char produto[30]; char seçao [30]; float preco; int cargo; }Supermercado;
Supermercado compra;
int main(void) {
soma2 = 0; do{
printf("\n\nEm qual seção está seu produto?");
printf("\n1-Frutas \n2-Doces \n3-Material de Limpeza\n --> ");
scanf("%d",&cod);
if(cod == 1){
*compra.seçao = *strcpy(compra.seçao,"Frutas");
}
if(cod == 2){
*compra.seçao = *strcpy(compra.seçao, "Doces");
}
if(cod == 3){
*compra.seçao = *strcpy(compra.seçao,"Material de Limpeza");
}
return 0;
printf("Informe o preço do produto: \n");
scanf("%f", &compra.preco);
soma2 = soma2 + compra.preco;
printf("\nDeseja mais algum produto? \n4-Sim \n0-Não, sair \n --> ");
scanf("%d",&cont); }while(cont == 4); {
if (cont == 0)
printf("\nFIM DAS COMPRAS!\n");
printf("Essa compra está custando: %i \n", soma2); } }
int Digitanome(char N[][40], int i)
{
printf("Informe o produto que você quer nesta seção: \n");
scanf("%s", & *N[i]);
*compra.produto = Digitanome( Nome, qtdNomes );
Lista( Nome, qtdNomes );
return ++i;
}
void Lista(char p[100][40], int i) { int j = 0; for (; j < i; j++ )
printf("\nSeus produtos são:%s\n", compra.produto); }

Trying to compile a x86 C program on a x64 RedHat environment [Part 2]

Still following the saga of a Cobol developer handling C programs on a environment migration.
I think we could manage 90% of the problems so far and most of our C programs are now compiling fine on the RHEL 64 bits.
Friday we found another module that is not compiling and I hope to be the last one.
I am receiving two warnings, but I have no idea about it and our make does not allow us to compile it properly.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <memory.h>
#include <errno.h>
#include </public/prod/src/mfqinc.h>
static FILE *infile = NULL;
static FILE *outfile = NULL;
char inbuf[1024], blockrec[10240];
static char workstring[1024];
static char workstring0[1024];
static char gra2533h [8];
static char gra2401h [8] ;
static char gra2501h [8] ;
static char gra2506h [8] ;
static char crtn[1] ; /* {"0x0A"};*/
int i;
int z;
int f;
int resulisn;
int j;
int d;
int ctrrec;
int nb_ecrit;
static int longueur;
void initworkstring()
{
extern char workstring [1024];
int ik;
for (ik=0; ik < 1024 ;ik++)
{
workstring [ik] = NULL;
}
}
void ecriture()
{
extern char workstring [1024];
extern int longueur;
extern int ctrrec;
nb_ecrit = fwrite(workstring,sizeof(char),longueur,outfile);
ctrrec++;
if ( nb_ecrit != longueur )
{
printf("andlog:erreur d ecriture ");
printf("Ecrit: %i",nb_ecrit);
printf("Erreur no: %i",errno);
exit(60);
}
}
static void errarg(char *errmsg)
{
fprintf(stderr,"ERROR - %s\nCommand format :\n\t",errmsg);
fprintf(stderr," : \n");
/* exit(1); */
}
main (int argc, char *argv[])
{
if ( argc < 3 )
{
printf("<<< Programme : and015 >>>\n");
printf("<<< Nombre de parametres incorrect >>>\n");
printf("<<< Remove catacteres speciaux >>>\n");
printf("<<< Param # 1 = nom du fichier d'input >>>\n");
printf("<<< Param # 2 = nom du fichier d'output >>>\n");
printf("\n");
exit(10);
}
if ((infile = fopen(argv[1],"rb")) == NULL )
{
printf("Erreur sur fichier input \n");
exit(20);
}
if ((outfile = fopen(argv[2],"wb")) == NULL )
{
printf("Erreur sur fichier output \n");
exit(30);
}
initworkstring();
/* remplir les table de catacteres */
crtn[0]=0x0a;
gra2533h[0]=0x1b;
gra2533h[1]=0x5b;
gra2533h[2]=0x32;
gra2533h[3]=0x35;
gra2533h[4]=0x3b;
gra2533h[5]=0x33;
gra2533h[6]=0x33;
gra2533h[7]=0x48;
gra2401h[0]=0x1b;
gra2401h[1]=0x5b;
gra2401h[2]=0x32;
gra2401h[3]=0x34;
gra2401h[4]=0x3b;
gra2401h[5]=0x30;
gra2401h[6]=0x31;
gra2401h[7]=0x48;
gra2501h[0]=0x1b;
gra2501h[1]=0x5b;
gra2501h[2]=0x32;
gra2501h[3]=0x35;
gra2501h[4]=0x3b;
gra2501h[5]=0x30;
gra2501h[6]=0x31;
gra2501h[7]=0x48;
gra2506h[0]=0x1b;
gra2506h[1]=0x5b;
gra2506h[2]=0x32;
gra2506h[3]=0x35;
gra2506h[4]=0x3b;
gra2506h[5]=0x30;
gra2506h[6]=0x36;
gra2506h[7]=0x48;
while (fgets(inbuf,1024,infile) != NULL )
{
i=0;
j=0;
d=0;
for (i=0; i < 1024 ; i++)
{
if ( inbuf [i] == NULL )
{
i = 9999;
}
else
{
if ( inbuf[i] == 0x1b )
{
i++;
d=0;
for (d=0 ;d < 8; d++)
{
if ( inbuf[i] == 0x48 )
{
j= j-d;
workstring[j]=0x0a;
d=99;
}
else
{
if (inbuf[i] == 0x6d)
{
j= j-d;
workstring[j]=0x0a;
d=99;
}
else
{
if (inbuf[i] == 0x53)
{
j=j-d;
workstring[j]=0x0a;
d=99;
}
else
{
workstring[j] = inbuf[i];
j++;
i++;
}
}
}
} /* end du for*/
}/*fin du if 01b*/
else
{
workstring[j] = inbuf[i];
j++;
}
}
/* mettre dans workstring */
workstring [j] = inbuf [i];
}
strcat(workstring,crtn);
longueur = j ;
ecriture ();
initworkstring();
} /* fin du while */
fclose(infile);
fclose(outfile);
exit(0);
}
Those are the warnings I am having.
/exp/prod/src>gcc -m64 mfqlog.c -o mfqlog
mfqlog.c: In function 'initworkstring':
mfqlog.c:48:20: warning: assignment makes integer from pointer without a cast [enabled by default]
workstring [ik] = NULL;
^
mfqlog.c: In function 'main':
mfqlog.c:146:18: warning: comparison between pointer and integer [enabled by default]
if ( inbuf [i] == NULL )
Really sorry to bother with this question. But I really need to compile this code.
The funny fact is that the program is working (probably, for some unknown reason to me, the program was compiling before and it is not anymore due to changes on the compiler maybe?!?) on our actual environment, but if we try to compile it will fail and the only way to make it working is restoring the executable backup.
As we are moving to a new 64 bits environment, it has to be recompiled.
Thank you all for the help.
NULL is defined as (void*)0. Replace NULL with '\0' or 0.
workstring [ik] = '\0';
if ( inbuf [i] == '\0' )

Issue with function that stopped my program

I have to do create a tree to register some passengers in it (from a plane flight) and then i will search them by their first letter.
My issue is that insert and print function work very well, but the search function do well for first time but when I want to do some other thing after in the main, it doesn't run the other function or things
(I tried to ask the user a letter, then use the function on research (works well here) but then for a second time to ask an other letter to user, and it prints "first letter of the person you are looking for" but i can't write the letter and it does not launch the function after this. so it stop the program there
int i;
char c;
typedef struct Passager
{
char nom[20];
char prenom[20];
int age;
int num_siege;
} Passager;
Passager liste_passagers[30]; //30 = nombre de passagers
typedef struct Arbre
{
Passager value;
struct Arbre *fils_gauche;
struct Arbre *fils_droit;
struct Arbre *racine;
} Arbre;
Arbre *const empty = NULL;
Arbre *passengers = empty; //passengers = arbre des passagers
/*--------------------------------------------*/
void liste_lettre_nom(Arbre *tree, char a)
{
Arbre *temp;
temp = tree;
if (!temp)
{
return;
}
else
{
if (a < temp->value.nom[0])
{
liste_lettre_nom(temp->fils_gauche, a);
}
if (a > temp->value.nom[0])
{
liste_lettre_nom(temp->fils_droit, a);
}
if (a == temp->value.nom[0])
{
printf("passager : \n");
print_passager(temp->value);
liste_lettre_nom(temp->fils_gauche, a);
liste_lettre_nom(temp->fils_droit, a);
}
}
}
/*--------------------------------------------*/
int main()
{
FILE* fichier = NULL;
fichier = fopen("/Users/Patoch/Desktop/Patoch /UNI/Informatique/info sem 2/Structure de données/Labo/TP3/Passager2.txt", "r");
if (fichier == NULL)
{ //test de la bonne ouverture du fichiers
printf("Impossible d'ouvrir le fichier Passagers.docx");
exit(EXIT_FAILURE);
}
for (i=0; i<(sizeof(liste_passagers)/sizeof(liste_passagers[0])); i++)
{
fscanf(fichier, "%s %s %d %d", liste_passagers[i].nom, liste_passagers[i].prenom, &liste_passagers[i].age, &liste_passagers[i].num_siege);
}
passengers = insertion(passengers, liste_passagers[1]);
passengers = insertion(passengers, liste_passagers[2]);
passengers = insertion(passengers, liste_passagers[0]);
passengers = insertion(passengers, liste_passagers[5]);
passengers = insertion(passengers, liste_passagers[26]);
print_arbre(passengers);
printf("-----------------------------\n");
printf("1ere lettre du nom de la personne recherchée: \n");
scanf("%c", &c);
liste_lettre_nom(passengers, c);
printf("-----------------------------\n");
printf("1ere lettre du nom de la personne recherchée: \n");
scanf(" %c", &c);
liste_lettre_nom(passengers, c);
destroy(passengers);
fclose(fichier);
return 0;
}

CodeBlocks project about passing arguments from pointer types

Here is the main function:
int main (void){
tProyecto proyecto; /*Proyecto a gestionar*/
int opcion; /*Opción del menú elegida*/
encabezado();
inicializarProyecto (proyecto);
do
{
opcion=menu();
switch (opcion)
{
case 1: altaInvestigadorEnProyecto (proyecto);
break;
case 2: listarProyecto (proyecto);
break;
case 3: asignarTareasAInvestigador (proyecto);
break;
case 4: borrarInvestigadorDelProyecto (proyecto);
break;
case 5: printf ("\nAdios. Gracias por utilizar este programa");
break;
default: printf ("\nNo es una opcion correcta. Por favor, introduzca un numero entre 1 y 5.");
}
}while (opcion!=5);
return 0;
}
Here the .h file
typedef char tDNI[MAX_DNI];
typedef char tNombre[MAX_NOMBRE];
typedef struct {
tNombre nombre;
tDNI dni;
tTareasAsignadas tareas;
} tInvestigador;
typedef struct {
tInvestigador investigador;
int ocupado; /*1 ocupado, 0 no ocupado */
} tCelda;
typedef tCelda tProyecto [MAX_INVES];
/* Extern functions prototype */
extern void altaInvestigadorEnProyecto(tProyecto* proyecto);
extern void listarProyecto(tProyecto* proyecto);
extern void inicializarProyecto(tProyecto* proyecto );
extern void borrarInvestigadorDelProyecto(tProyecto* proyecto);
extern void asignarTareasAInvestigador(tProyecto* proyecto);
The problem in CodeBlocks words is "warning: passing argument 1 of 'inicializarProyecto' from incompatible pointer type--note: expected 'struct tCelda (*)[3]' but argument is of type 'struct tCelda *"
I understand this means that the function expects a struct array but I'm sending just a struct to it. I don't know how to design it so it works that way. The problem is on the calling of the functions in the main and in the "extern void" functions. I'd really appreciate if someone could tell me how to do it.
This are the functions where the pointer is used:
void altaInvestigadorEnProyecto(tProyecto* proyecto){
tNombre nombre;
tDNI dni;
int salida = 0;
if (haySitioEnProyecto(proyecto, &salida) == 1){
printf("\nIntroduzca el investigador a dar de alta: \n");
scanf("%s\n", nombre);
if (strncmp(proyecto[salida]->investigador.nombre, nombre, MAX_NOMBRE)
!= 0){
printf("\nIntroduzca el DNI del investigador a dar de alta: \n");
scanf("%s\n", dni);
proyecto[salida]->ocupado = 1;
strncpy(proyecto[salida]->investigador.nombre, nombre, MAX_NOMBRE);
strncpy(proyecto[salida]->investigador.dni, dni, MAX_DNI);
}
}
}
int haySitioEnProyecto(tProyecto * proyecto, int * sitio){
int ok = 0;
int i;
for (i=0; (i<MAX_INVES) && (ok == 0); i++){
if (proyecto[i]->ocupado == 0){
ok = 1;
*sitio = i;
}
}
return ok;
}
void listarProyecto(tProyecto * proyecto){
int i;
printf("/nProyecto: \n");
for(i=0; i<MAX_INVES; i++){
if (proyecto[i]->ocupado == 1){
printf("/nInvestigador:\n");
printf("/n/tNombre: %s: \n", proyecto[i]->investigador.nombre);
printf("/n/tDNI: %s: \n", proyecto[i]->investigador.dni);
printf("/n/tTareas:\n");
listarTareasAsignadas(proyecto[i]->investigador.tareas);
}
}
}
void asignarTareasAInvestigador(tProyecto * proyecto){
tDNI dni;
int posicion = 0;
int aniadir = 0;
int i;
listarProyecto(proyecto);
printf("\nIntroduzca el DNI del investigador al que se quiere asignar
tareas: \n");
scanf("%s\n", dni);
if (buscarInvestigadorPorDNI(proyecto, dni, &posicion) == 1){
for (i = 0; i < (MAX_TAREAS - proyecto[posicion]-
>investigador.tareas.numeroTareasAsignadas); i++){
printf("/n¿Quiere aniadir una tarea?: (0: no quiero; 1: quiero)\n");
scanf("%u\n", &aniadir);
if (aniadir == 1){
if (proyecto[posicion]-
>investigador.tareas.numeroTareasAsignadas < MAX_TAREAS){
aniadirTarea(&(proyecto[posicion]->investigador.tareas));
}
}
}
}
}
int buscarInvestigadorPorDNI(tProyecto * proyecto, tDNI dni, int * posicion)
{
int ok = 0;
int i;
for (i = 0; (i < MAX_INVES) && (ok == 0); i++){
if (strncmp(proyecto[i]->investigador.dni, dni, MAX_DNI) == 0){
ok = 1;
*posicion = i;
}
}
return ok;
}
void borrarInvestigadorDelProyecto(tProyecto * proyecto){
tDNI dni;
int posicion = 0;
listarProyecto(proyecto);
printf("\nIntroduzca el DNI del investigador que quiere eliminar: \n");
scanf("%s\n", dni);
if (buscarInvestigadorPorDNI(proyecto, dni, &posicion) == 1){
proyecto[posicion]->ocupado = 0;
strncpy(proyecto[posicion]->investigador.nombre, "", MAX_NOMBRE);
strncpy(proyecto[posicion]->investigador.dni, "", MAX_DNI);
inicializarTareasAsignadas(&(proyecto[posicion]->investigador.tareas));
}
}
Well the problem is - you have called it wrong.
inicializarProyecto (proyecto);
will be
inicializarProyecto (&proyecto);
That will solve the warning message. First one had type of tCelda * but the second one will be tCelda (*)[MAX_INVES] which in turn matches with the pointer to the typedef-ed type tProyecto (which is basically tCelda [MAX_INVES]).
That means wherever you have tProyecto * proyecto pass &proyecto and then in the functions you will access it like this
(*proyecto)[i].ocupado = 1;
or
proyecto[0][i].ocupado = 1;
where i is obviously i>=0 and i<=MAX_INVES-1.

segmentation fault rewind

Could you explain me why after a rewind(f) in the function "recuperationdeNS", I have a Segmentation Fault ?
The second printf in the function "recuperationdeNS" doesn't appear. The segmentation fault stopped the program before.
I'm sure that the name of the file is ok.
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include"procedurecommune.h"
#include"procedureGenA.h"
#include"procedureGenO.h"
void ouvrir_fic(FILE** f, char* nom,char* type)
{
*f=fopen(nom,type);
if(f==NULL)
{
printf("probleme lecture ou ecriture du fichier : %s\n",nom);
exit(2);
}
}
int recuperationdeNS(FILE* fichG)
{
printf("aloooooooooo\n");
int i, N;
char chaine [2000];
rewind(fichG);
printf("aloooooooooo\n");
for(i=0;i<2;i++) // on saute les lignes de commentaires
{
fgets(chaine, sizeof chaine, fichG);
printf("chaine :%s\n",chaine);
}
fscanf(fichG, "%d",&N); // recuperation de N
return (N);
}
void recuperationnomfichiergena(FILE* fichG, char** NomFichierGenA, int nbligneasauter)
{
int i,c,iemecaractereligne;
rewind(fichG);
char chaine [Nmcl];
for(i=0;i<nbligneasauter;i++) // on saute les lignes de commentaires
{
fgets(chaine, sizeof chaine, fichG);
}
*NomFichierGenA=(char*) malloc (sizeof(char)*Nmcl);
fgets(chaine, sizeof chaine, fichG);
iemecaractereligne=0;
c=chaine[iemecaractereligne];
while(c != '\n')
{
c=chaine[iemecaractereligne];
if(c !='\n')
{
(*NomFichierGenA)[iemecaractereligne]=c;
}
iemecaractereligne++;
}
}
int determinationtypedegenchoisi(FILE* fichG);
int recuperationdeN(FILE* fichG);
void recuperationtabentiergenencours(FILE* fichG,int* genencours, int N);
void recuperationnomfichiergena(FILE* fichG, char ** nomfich,int nbligneasauter);
void main(int args, char **argv)
{
FILE * fichG=NULL;
FILE * fichM=NULL; //fichier contenant le contexte
FILE * fichMgenParAtt=NULL; //fichier contenant le contexte pregeneralise par attribut
FILE * fichGA=NULL; //fichier contenant la matrice de generalisation attribut
FILE * fichGO=NULL;
int** Matricegenereextraite;
int typedegen;
int i,nbligneMat,nbcolonneMat,nbgroupegeneralisant1,nbgroupegeneralisant2;
char NomUniqueFichierGen[Nmcm];
char chaine[Nmcl];
char* NomFichGenExtraitA;
char* NomFichGenExtraitO;
char* NomFichGenExtraitFinale;
char* NomFichierGenA ;
char* NomFichierGenO;
char* chaineNva;
char* chaineNvo;
int Na, No;
int N, Ni;
int* nbgroupegeneralisant;
int nbgroupegeneralisantmax;
const int nbligneenteteGparun = 5;//nombre de ligne pour acces nom fichier de gen attribut
const int nbligneenteteGpardeux = 8;//nombre de ligne pour acces nom fichier de gen objet
int* genencours;
NomFichGenExtraitA=argv[3];
NomFichGenExtraitO=argv[4];
NomFichGenExtraitFinale=argv[5];
chaineNva= argv[6];
chaineNvo= argv[7];
char dernierephrase[]="Name_of_dataset\n";
char* nomsdesobjets;
char** nomsdesgroupes;
char* nomsdesattributs;
int*** Matrice;
//Nva=chaineNva[0]-'0';
//Nvo=chaineNvo[0]-'0';
/// ouverture des fichiers
ouvrir_fic(&fichG, argv[2],"r");
ouvrir_fic(&fichM, argv[1],"r");
///////////////////////////////////////////////
//info du fichier Gen.txt
typedegen=determinationtypedegenchoisi(fichG);
printf("typedegen: %d\n",typedegen);
N=recuperationdeN(fichG);
printf("N: %d\n",N);
allocationdynamiquetableauunedimdentier(&genencours, N);
recuperationtabentiergenencours(fichG,genencours,N);
///////////////////recuperation choix de gen
//////////////////////////////////////////////////
//info du fichier Matrice.txt
nblignecolonneMat(fichM,&nbligneMat,&nbcolonneMat,dernierephrase);
printf("nbligneMat :%d, nbcolonneMat :%d\n",nbligneMat, nbcolonneMat);
///lecture du noms des objets et des attributs
objetsetattributs(fichM, &nomsdesobjets,&nomsdesattributs, dernierephrase);
printf("nomsdesO : %s\n",nomsdesobjets);
printf("nomsdesA : %s\n",nomsdesattributs);
//allocation dynamique
allocationdynamiquetableautroisdimdentier(&Matrice,N,nbligneMat,nbcolonneMat);
/// recuperation de la matrice de depart
recuperationmatrice (fichM, Matrice[0], nbligneMat, nbcolonneMat);
printf("\nMatrice 0:\n");
affichageMatrice(0, nbligneMat, 0, nbcolonneMat, Matrice[0]);
typedegen=1;
if(typedegen==1)
{
//////////////////////////////////////////
//info du fichier genO.txt
recuperationnomfichiergena(fichG, &NomFichierGenO,nbligneenteteGpardeux);
printf("fichier de generalisation utilise :%s\n ",NomFichierGenO);
ouvrir_fic(&fichGO, NomFichierGenO,"r");
No=recuperationdeNS(fichGO);
printf("No :%d\n",No);
}
}
Your file open check in ouvrir_fic() is faulty:
void ouvrir_fic(FILE** f, char* nom,char* type)
{
*f=fopen(nom,type);
if(f==NULL)
{
printf("probleme lecture ou ecriture du fichier : %s\n",nom);
exit(2);
}
}
You should be checking whether *f is NULL; you've already assumed that f is not null when you made the assignment.
Since the file failed to open, you have a null pointer in *f.
I'd probably use:
FILE *ouvrir_fic(const char *nom, const char *mode)
{
FILE *fp = fopen(nom, mode);
if (fp == NULL)
{
fprintf(stderr, "probleme lecture ou ecriture du fichier: %s\n", nom);
exit(2);
}
return(fp);
}
This may be contributing to the problem:
*f=fopen(nom,type);
if(f==NULL)
The if check does not check if the file was opened (only checks if the f argument is not null, after it has been used). If fopen() fails the file pointer will be NULL and it will be undetected. The check should be:
if (*f == NULL)

Resources