如何使用函数动态分配字符串?

How to dynamically allocate a string using function?

我正在尝试通过接受用户来分配动态字符串。我想用一个函数来做。我正在尝试实现以下代码,但它无法正常工作。

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

int string(char *str)
{
    char c; 
    int i=0,j=1;
    str = (char*)malloc(sizeof(char));

    printf("Enter String : ");
    while(c!='\n')
    {
        c = getc(stdin);     //read the input from keyboard standard input
        //re-allocate (resize) memory for character read to be stored
        *str = (char*)realloc(str,j*sizeof(char));
        *str[i] = c;  //store read character by making pointer point to c
        i++;
        j++;
    }
    str[i]='[=10=]';   //at the end append null character to mark end of string
    printf("\nThe entered string is : %s",str);
    return j;    
}


int main()
{
    int len;
    char *str=NULL;
    len=string(str);
    printf("\nThe entered string is : %s and it is of %d length.",str,len);
    free(str);    
    return 0;
}

您需要传递对指针 (int string(char **str)) 的引用,因为您要在函数内部更改 str 的值。

main 你应该调用 string(&str)

问题数量:

  1. 内存太小

  2. while(c!='\n') 第一次测试 c 即使它是未初始化的。

  3. string() 应该传递 char * 的地址,如 string(char **)

  4. 在使用 strlen() 时最好使用 size_t 而不是 int

未成年人:

  1. 未检测到 EOF。使用 int c 而不是 char c 来帮助检测。

  2. 每个循环realloc()肯定效率低下。

  3. 不需要转换 malloc()/realloc()

  4. 检查内存是否不足。

  5. 为了便携性,使用 int main(void) 而不是 int main()

    size_t string(char **str) {
      assert(str);
      int c; 
      size_t i = 0;
      size_t size = 0;
      *str = NULL;
    
      printf("Enter String : ");
      while((c = getc(stdin)) !='\n' && c != EOF) {
        if (i == size) {
          size *= 2 + 1;         // double the size each time
          *str = realloc(*str, size);
          assert(*str);
        }
        (*str)[i] = c;           // store read character by making pointer point to c
        i++;
      }
      *str = realloc(*str, i+1); // right-size the string
      assert(*str);
      (*str)[i] = '[=10=]';          // at the end append null character to mark end 
      printf("\nThe entered string is : %s",*str);
      return i;    
    }