首页 > 解决方案 > 每个字符串长度的动态 n 个字符串是随机的(取决于用户输入)

问题描述

我正在写如何为 n 个字符串动态分配内存,每个字符串只要你想要的长。所以我知道使用双指针,但不明白如何为每个字符串分配合适的空间。我的代码:

     int i,n;
     char **str;

    printf("Enter n (strings of chracters): ");
    scanf("%d",&n);

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

    printf("Enter strings one by one:\n");
    for(i=0; i<n; i++) {
        str[i] = (char*)malloc(//SOMETHING//*sizeof(char));
        gets(str[i]);
    }

我试着厚脸皮,像这样把gets()放在第一位

for(i=0; i<n; i++) {
        gets(str[i]);
        str[i] = (char*)malloc(strlen(str[i])*sizeof(char));

但这显然是错误的,我无法读取字符串然后分配它。
那么无论如何用每个字符串的长度替换//SOMETHING//?感谢您阅读我的业余帖子。

标签: cpointers

解决方案


如果您不想浪费空间并且只分配足够的内存来容纳字符串,那么您需要逐个字符地读取,直到您读取换行符,realloc并根据需要重新分配(使用)。

也许是这样的:

for (i = 0; i < n; ++i)
{
    size_t current_size = 1;  // Start with space for one character, the null-terminator
    str[i] = malloc(current_size);
    str[i][0] = '\0';  // String null-terminator

    int ch;  // Must be an int for the EOF check to work

    // Read characters one by one, until eof (or error) or newline
    while ((ch = getchar()) != EOF && ch != '\n')
    {
        char *temp_str = realloc(str[i], current_size + 1);  // Increase memory by one character
        if (temp_str == NULL)
        {
            // Error allocating memory, do something useful here
            break;
        }

        str[i] = temp_str;
        str[i][current_size - 1] = ch;  // Add the newly read character
        str[i][current_size] = '\0';  // Add the new null-terminator
        ++current_size;  // Increase the size
    }
}

推荐阅读