0

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
yepitis
  • 23
  • 4
  • 1
    Using `printf("%d",p[j]);` for output, you will only get numbers printed, will you not? – Jonathan Leffler Jan 14 '20 at 03:26
  • @JonathanLeffler, I'm not the one asking the question, so I have to go with what the OP posted. And (IMO) posting code is extremely simple. Just indent every line of the code 4 spaces above what the original source indented the code. – user3629249 Jan 14 '20 at 03:50

1 Answers1

4
  1. puntatoreI = &i;
    

    Is assigning a pointer puntatoreI to point to variable i. You don't want to do that. You want to modify variable i inside main, that is where the pointer puntatoreI points to. You want:

    *puntatoreI = i;
    
  2. You are allocating (i+1) characters for p. Yet you are assigning to p[i+1] = '\0'; is accessing 1-byte out of bounds. Just p[i] = '\0';. i is the last index in an array of i+1 elements.

  3. Using empty braces in function declaration char *fw(); is very old. To make sure your code is ok, just repeat the function declaration from the definition char *fw(char *parola, int *puntatoreI);.

  4. The type of &parola is char (*)[30] - it's a pointer to an array of 30 characters. Yet, the fw function takes char * - a pointer to char. Just pass parola as in p = fw(parola, &i);.

  5. And finally, to your question:

    why when I execute it I get a bunch of numbers in output.

    You get a "bunch of numbers" on the output, because you print them with printf("%d",p[j]);. %d is a printf format specifier used to print numbers in base 10. To print characters as they are, use %c format specifier. But because p should point to a zero-terminated array of characters (to a string), you could do just printf("%s", p); instead of the whole loop.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
KamilCuk
  • 120,984
  • 8
  • 59
  • 111