Your code has two issues:
1.
scanf("%s", &a);
The argument a
already decays to a pointer to the first element of array a
-> so the type of it as argument is actually char *
. Thus, &a
is of type char (*)[1000]
.
There is a type mismatch to the expected argument of type char *
for the %s
conversion specifier.
If you use GCC as compiler, the -Wall
option (or respectively -Wformat=
) had showed you a warning about this:
warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[1000]' [-Wformat=]
9 | scanf("%s",&a);
| ~^ ~~
| | |
| | char (*)[1000]
| char *
2.
Furthermore, if you need to store an integral number up to 1000 digits - which includes the case of a 1000 digit integer, you forgot that you need one element more to store the string-terminating null character ('\0'
):
char a[1001];
Else, if the user inputs a number of 1000 digits, the null character would be stored beyond the bounds of the array, which invokes undefined behavior.
Additionally:
Use a length modifer to ensure there will occur no buffer overflow if the user attempts to enter a number of more than 1000 digits:
scanf("%1000s", a);
or use fgets()
which is ensures this by default as it requires the number of characters to be written as second argument.
fgets(a, sizeof(a), stdin);
sizeof(a)
is appropriate as sizeof(char)
is always 1
. It obtains the number of elements, a
has.
Result:
#include <stdio.h>
int main (void) {
char a[1001];
int i = 0;
printf("Please enter an integral number up to 1000: ");
fgets(a, sizeof(a), stdin);
// scanf("%1000s", a); Alternative to previous fgets.
while (a[i] != 0) {
printf("%c\n", a[i]);
i++;
}
printf("\n");
return 0;
}