Reputation: 307
Is there any way I can do this without using dynamic memory allocation?
#include <stdio.h>
int main() {
char* str = NULL;
scanf("%s", str);
printf("%s\n", str);
}
Upvotes: 1
Views: 80
Reputation: 331
Yes, but you are going to waste memory, or have the risk of segmentanltion violation:
#include <stdio.h>
int main() {
char str[512] = {0} // as suggested by Jabberwocky
//sprintf(str, "");
//scanf("%s", str); // protecting the input from more than 511 chars
scanf("%511s", str);
printf("%s\n", str);
}
Upvotes: -1
Reputation: 134316
There is no straightforward way as per the C
standard (C11
), however, POSIX defines optional assignment-allocation character m
as part of the conversion specifier, which relives the programmer from the responsibility of allocating memory.
However, under the hood, this does use dynamic memory allocation, and you need to call free()
on the pointer later on.
Quoting the reference:
The
%c
,%s
, and%[
conversion specifiers shall accept an optional assignment-allocation character'm'
, which shall cause a memory buffer to be allocated to hold the string converted including a terminating null character. In such a case, the argument corresponding to the conversion specifier should be a reference to a pointer variable that will receive a pointer to the allocated buffer. The system shall allocate a buffer as ifmalloc()
had been called. The application shall be responsible for freeing the memory after usage. If there is insufficient memory to allocate a buffer, the function shall seterrno
to[ENOMEM]
and a conversion error shall result. If the function returnsEOF
, any memory successfully allocated for parameters using assignment-allocation character'm'
by this call shall be freed before the function returns.
Something like
#include <stdio.h>
#include <stdlib.h>
int main() {
char* str = NULL;
scanf("%ms", &str);
printf("%s\n", str);
free(str);
return 0;
}
would do the job.
Upvotes: 6
Reputation: 751
This way:
int main()
{
char str[100];
scanf("%s", str);
printf("%s\n", str);
}
Upvotes: 0