dodo
dodo

Reputation: 3

Dynamically allocate string to contain user input in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void){
  char* a;
  scanf("%s",a);
  printf("%s", a);
  free(a);
  return 0;
}

My question is dynamic allocation without static declaration.

I want to do dynamic assignment with just in the input statement. Internal code or Not by a static declaration... However, dynamic allocation is not possible with the above input this code. Is there any other way? By not touching the inner code or making static declarations.

Upvotes: 0

Views: 250

Answers (1)

Andy Sukowski-Bang
Andy Sukowski-Bang

Reputation: 1420

You could use realloc from <stdlib.h> to achieve it.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    fputs("Input: ", stdout);
    char *str = malloc(1);

    int c, i;
    for (i = 0; (c = fgetc(stdin)) != '\n' && c != EOF; ++i) {
        str[i] = c;
        str = realloc(str, i + 2);
    }
    str[i] = '\0';

    printf("Output: %s\n", str);
    free(str);

    return EXIT_SUCCESS;
}

But I would not advise you to do that, because it can be expensive depending on the implementation. Instead I would just create a string with fixed size and prevent a buffer overflow.

char str[20];
scanf("%19s", str);

Or using fgets:

char str[20];
fgets(str, 20, stdin);

Upvotes: 1

Related Questions