How to dynamically allocate memory space for a str

2019-01-02 23:01发布

I want to read input from user using C program. I don't want to use array like,

char names[50];

because if the user gives string of length 10, then the remaining spaces are wasted.

If I use character pointer like,

char *names;

then I need to allocate memory for that in such a way of,

names = (char *)malloc(20 * sizeof(char));

In this case also, there is a possibility of memory wastage.

So, what I need is to dynamically allocate memory for a string which is of exactly same as the length of the string.

Lets assume,

If the user input is "stackoverflow", then the memory allocated should be of 14 (i.e. Length of the string = 13 and 1 additional space for '\0').

How could I achieve this?

10条回答
混吃等死
2楼-- · 2019-01-02 23:07

Here's a snippet which I wrote which performs the same functionality.

This code is similar to the one written by Kunal Wadhwa.

char *dynamicCharString()
{
char *str, c;
int i;
str = (char*)malloc(1*sizeof(char));

while(c = getc(stdin),c!='\n')
{
    str[i] = c;
    i++;
    realloc(str,i*sizeof(char));
}
str[i] = '\0';
return str;
}
查看更多
干净又极端
3楼-- · 2019-01-02 23:11

You can also use a regular expression, for instance the following piece of code:

char *names
scanf("%m[^\n]", &names)

will get the whole line from stdin, allocating dynamically the amount of space that it takes. After that, of course, you have to free names.

查看更多
Animai°情兽
4楼-- · 2019-01-02 23:13

Below is the code for creating dynamic string :

void main()
{
  char *str, c;
  int i = 0, j = 1;

  str = (char*)malloc(sizeof(char));

  printf("Enter String : ");

  while (c != '\n') {
    // read the input from keyboard standard input
    c = getc(stdin);

    // re-allocate (resize) memory for character read to be stored
    str = (char*)realloc(str, j * sizeof(char));

    // store read character by making pointer point to c
    str[i] = c;

    i++;
    j++;
  }

  str[i] = '\0'; // at the end append null character to mark end of string

  printf("\nThe entered string is : %s", str);

  free(str); // important step the pointer declared must be made free
}
查看更多
乱世女痞
5楼-- · 2019-01-02 23:13
char* load_string()
 {

char* string = (char*) malloc(sizeof(char));
*string = '\0';

int key;
int sizer = 2;

char sup[2] = {'\0'};

while( (key = getc(stdin)) != '\n')
{
    string = realloc(string,sizer * sizeof(char));
    sup[0] = (char) key;
    strcat(string,sup);
    sizer++

}
return string;

}

int main()
  {
char* str;
str = load_string();

return 0;
  }
查看更多
时光不老,我们不散
6楼-- · 2019-01-02 23:14

This is more simple approach

char *in_str;
in_str=(char *)malloc(512000 * sizeof(char));
enter code herescanf("\n%[^\n]",in_str);
查看更多
叼着烟拽天下
7楼-- · 2019-01-02 23:14

This is a function snippet I wrote to scan the user input for a string and then store that string on an array of the same size as the user input. Note that I initialize j to the value of 2 to be able to store the '\0' character.

char* dynamicstring() {
    char *str = NULL;
    int i = 0, j = 2, c;
    str = (char*)malloc(sizeof(char));
    //error checking
    if (str == NULL) {
        printf("Error allocating memory\n");
        exit(EXIT_FAILURE);
    }

    while((c = getc(stdin)) && c != '\n')
    {
        str[i] = c;
        str = realloc(str,j*sizeof(char));
        //error checking
        if (str == NULL) {
            printf("Error allocating memory\n");
            free(str);
            exit(EXIT_FAILURE);
        }

        i++;
        j++;
    }
    str[i] = '\0';
    return str;
}

In main(), you can declare another char* variable to store the return value of dynamicstring() and then free that char* variable when you're done using it.

查看更多
登录 后发表回答