Home > Back-end >  How to make a dynamic string?`I want to get a string dynamically but i don;t what to use it like thi
How to make a dynamic string?`I want to get a string dynamically but i don;t what to use it like thi

Time:01-31

#include<stdio.h>
#include<string.h>
int main()
{
    char string[100];
    printf("Enter string: ");
    fgets(string, 100, stdin);
    return 0;
}

Or we can also do something like this:

char **string;
string = (char **)malloc(100 * sizeof(char*));

CodePudding user response:

Arrays either have fixed or dynamic size in C, they can't have both. When taking user input, it is perfectly sensible to use a fixed size array, because taking "infinite input" doesn't make any sense.

If there's a lot of data to store, then you can copy it from the fixed size array to a dynamic one once the input is verified.

The only sensible way of allocating an array dynamically is to use malloc (family of functions). It is done as char* arr = malloc(100);, no need for casting of taking the size of a character. "I don't want to" isn't a great rationale, this is how the language works.

As for char **string; string = (char *)malloc(100 * sizeof(char)); it is simply wrong and doesn't make any sense. If you wish to declare an array of pointers it is char** arr = malloc(n * sizeof(char*)). This only allocates room for the pointers though, not the data pointed at by them.

Alternatively you can use variable-length arrays (VLA) such as int n=100; char array[n]; but this isn't recommended practice beyond temporary store of small objects. VLA often get allocated on the stack and their storage duration is limited to the block where it was declare. Therefore excessive use of them might chew up all stack space and they also turn invalid soon as you leave the scope where you declared it.

For beginners, I'd say that malloc is recommended over VLA.

CodePudding user response:

Re: How to make a dynamic string?`I want to get a string dynamically but i don;t what to use it like this: string = (char*)malloc(100 * sizeof(char));

So wash me, but don't make me wet?

There is no other way to make a dynamic string without one of the memory allocation functions.

Languages are tools, if you find dynamic allocation complicated in C, try another language (one that does it for you and has a built-in string type).

If that's not feasible, then you're stuck with good ol' malloc() and realloc().

But as @Lundin said, it's not sensible to allow input forever (one vulnerability POSIX's getline() has), you should specify an upper limit, and if the input exceeds that, consider it a DOS attack and deny service to the attacker.

CodePudding user response:

Memory allocation in C is quite low-level and error prone so it's a good idea to define functions which are easier to use correctly. The problem with fgets is that it reads also the trailing newline character and that it doesn't consume the entire line. Therefor I usually define my own ReadLine function. Below are a few handy declarations and example usage of both static and dynamic character arrays. If you put the declarations in a separate header and implementation file you can use them in all your applications (like I do).

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

#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])

#define NEW_ARRAY(ptr, n) \
    (ptr) = malloc((n) * sizeof (ptr)[0]); \
    if ((ptr) == NULL) { \
        fprintf(stderr, "Memory allocation failed: %s\n", strerror(errno)); \
        exit(EXIT_FAILURE); \
    }

void ReadLine(char result[], int resultLen)
{
    int ch, i;

    i = 0;
    ch = getchar();
    while ((ch != '\n') && (ch != EOF)) {
        if (i < resultLen - 1) {
            result[i] = ch;
            i  ;
        }
        ch = getchar();
    }
    result[i] = '\0';
}

int main(void)
{
    char string[100];
    char *anotherString;
    int anotherStringLen;
    
    printf("Enter string: ");
    ReadLine(string, LEN(string));
    printf("You entered '%s'\n", string);
    
    anotherStringLen = 200;
    NEW_ARRAY(anotherString, anotherStringLen);
    printf("Enter another string: ");
    ReadLine(anotherString, anotherStringLen);
    printf("You entered '%s'\n", anotherString);
    free(anotherString);
    
    return 0;
}
  • Related