I have written this script, and the aim of it is to get in input a phrase and to print just the first word (the one before the first space). I cannot understand why, when I execute it, I get a bunch of numbers in the output.
#include <stdio.h>
#include <stdlib.h>
#define MAX 30
/*
Prende in input una frase e stampa la prima parola
*/
char *fw();
int main () {
int j,i;
char parola[MAX], *p;
printf ("Inserisci una stringa: ");
fgets(parola, MAX, stdin);
p = fw(&parola, &i);
for (j=0; j < i; j++){
printf("%d", p[j]);
}
return 0;
}
char *fw(char *parola, int *puntatoreI) {
int i;
char *p;
for (i=0; parola[i]!=' '; i++)
;
p = (char *)malloc((i+1)*sizeof(char));
for (i=0; parola[i]!=' '; i++){
p[i] = parola[i];
}
p[i+1] = '\0';
puntatoreI = &i;
return p;
}