char sentence[] = "";
That creates an array containing one character, a null character that marks the end of a string.
Once created, the size of that array cannot be changed.
scanf("", &sentence);
This scanf
has no conversion specifier, like %s
, that tells it what to expect in input and how to store it. If it did have %s
, then &sentence
would be the wrong thing to pass it. For %s
, you should pass a pointer to char
, but the type of &sentence
is a pointer to an array of char
.
You could pass the correct type of pointer by passing sentence
, as in scanf("%s", sentence);
. Although sentence
is an array, it will be automatically converted to a pointer to its first element, hence a pointer to char
. However, this is still not useful as the array is not large enough to hold any string other than the string with no characters.
If I'm correct, a value will automatically be assigned to the array that is sufficient to accommodate the string that is entered by the user.
This is not correct. The standard C scanf
will not allocate memory for strings.
The GNU C Library and POSIX have an extension to scanf
in which you can use %ms
as a conversion specifier, and it will allocate space. In this case, you need to pass a pointer to a pointer to a char
, not a pointer to an array of char
:
char *sentence;
int result = scanf("%ms", &sentence);
if (result != 1)
{
fprintf(stderr, "Error, scanf did not work as desired.\n");
exit(EXIT_FAILURE);
}
Is there a way I can assign this value to a variable or something so that Ican recall it later?
After a successful call to scanf
using %ms
, you can find the length of the string that was read using strlen
, as in strlen(sentence)
.