0
char getString(char *str, int length, char field[20])
{
    printf(" %s: ", field);
    fflush(stdin);
    fgets(str, length, stdin);
    str[strlen(str) - 1] = '\0';
    fflush(stdin);
    return *str;
}

why i can't use strcpy in this case

strcpy(newContact->fieldsValue[i], getString(newContact->fieldsValue[i], 30, listFieldsName[i]));

i want to get value of fieldName

struct newContact = {
char *fieldsName[30],
char *fieldsValue[30],
struct newContact* next;
}
char *listFieldsName = {"a", "b", "c"};
nomnom
  • 17
  • 4
  • You can't use `strcpy` because `strcpy` is used to copy strings. You only provide a single `char`. That is not a string. Strings are nul-termianted character sequences. Unless your string has length 0 it won't fit into a single `char`. And even in that case, you would need to provide the address of that `char`. – Gerhardh Jan 14 '23 at 11:00
  • 1
    Not your question, but: https://stackoverflow.com/questions/2979209/using-fflushstdin – Paul Hankin Jan 14 '23 at 11:02
  • Can you fix the formatting of your code please? You've blamed it on stackoverflow, but most people asking questions manage to format their code without backslashes... – Paul Hankin Jan 14 '23 at 11:06
  • sorry, i will fix formatting of my code – nomnom Jan 14 '23 at 11:12

1 Answers1

0

Undefined Behaviour:

fflush(stdin);

Flushing stdin invokes undefined behaviour.

From C11:

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

  • Once the abstract state machine reaches an undefined state, no further assumption about the continuation of the execution of the program can be made.

Re: Why can't I use strcpy in this case?

Invalid arguments to strcpy:

From C11:

The strcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

The function strcpy takes the source string and destination string, where a string is an array of null-terminated bytes.

Answer: getstring returns a char, not a char *. You're passing a char in place of a char * to strcpy.

Harith
  • 4,663
  • 1
  • 5
  • 20
  • but im using fgets so i cant return char in getString() – nomnom Jan 14 '23 at 11:56
  • You don't need to return anything. Just call the function before ```strcpy``` and pass ```str``` directly to it. But it's hard to tell what you're trying to do without seeing your code. Kindly edit the question to provide a minimal reproducible example. – Harith Jan 14 '23 at 12:05