动态分配c中的双指针

问题描述 投票:0回答:2

这个问题是this question的延续。

这是代码:

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

int main(void)
{
    int ch;
    char *ptrChFromFile;
    char **ptrWords;
    int strSize = 1;
    int i;
    int j = 0;
    int numberOfWords = 1;

    ptrChFromFile = malloc(sizeof(char));

    if (ptrChFromFile == NULL)
    {
        puts("COULDN'T ALLOICATE MEMORY");
        exit(EXIT_FAILURE);
    }

    while ((ch = getchar()) != '\n')
    {
        ptrChFromFile = realloc(ptrChFromFile, (strSize+1) * sizeof(char));

        if (ptrChFromFile == NULL)
        {
            puts("failed to allocate memory");
            exit(EXIT_FAILURE);
        }

        if (ch == ' ')
        {
            numberOfWords++;
        }

        ptrChFromFile[strSize] = ch;
        strSize++;
    }

    ptrChFromFile[strSize] = 0;

    ptrWords = malloc(sizeof(char*) * numberOfWords); //creates number of slots in ptr

    if (ptrWords == NULL)
    {
        puts("failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < numberOfWords; i++) // allocates number of bytes in each slot.
    {
        ptrWords[i] = malloc(sizeof(char*)* strSize);
        if (ptrWords[i] == NULL)
        {
            puts("failed to allocate memory");
            exit(EXIT_FAILURE);
        }
    }

    for (i = 0; i < strSize; i++)
    {
        if (ptrChFromFile[i] != ' ')
        {
            ptrWords[j] = &ptrChFromFile[i];
        }
        else
        {
            ptrWords[j] = 0;
            j++;
        }
    }

    for (i = 0; i < numberOfWords; i++) // free's each slot in ptrWords
    {
        free(ptrWords[i]);
    }

    free(ptrChFromFile);
    free(ptrWords);
    return 0;
}

我试图动态分配我的双字符指针ptrWords。请允许我解释一下我的思考过程:

ptrWords = malloc(sizeof(char*) * numberOfWords); //creates number of slots in ptr

这会在ptrWords中创建槽数(索引)。所以如果我有3个字,ptrWords应该是这样的:

ptrWords [索引0]

ptrWords [索引1]

ptrWords [索引2]

for (i = 0; i < numberOfWords; i++) // allocates number of bytes in each slot.
{
    ptrWords[i] = malloc(sizeof(char*)* strSize);
    if (ptrWords[i] == NULL)
    {
        puts("failed to allocate memory");
        exit(EXIT_FAILURE);
    }
}

这个for循环为ptrWords中的每个槽分配内存,等于输入文件中的字符总数。因此,如果输入文件总共有26个字符,那么ptrWords中的每个插槽将分配26个字节。

ptrWords [index 0]有26个字节的内存

ptrWords [索引1]有26个字节的内存

ptrWords [索引2]有26个字节的内存

我认为我对ptrWords的记忆分配是正确的,但我不确定。

for (i = 0; i < strSize; i++)
{
    if (ptrChFromFile[i] != ' ')
    {
        ptrWords[j] = &ptrChFromFile[i];
    }
    else
    {
        ptrWords[j] = 0;
        j++;
    }
}

这个for循环应该从ptrChFromFile获取字符并将它们作为单独的单词存储在ptrWords中。我的循环逻辑如下:

1)只要ch不等于空格,取该字符并将其存储在ptrWords的第一个位置(索引0)。

2)如果ch确实等于空格,则在其位置放置一个终止字符('\ 0')然后将j递增1以移动到ptrWords中的下一个索引以存储下一个单词。

我已经使用调试器来逐步完成代码,但我仍然无法弄清楚什么是错误的,所以任何帮助都会受到赞赏。

谢谢


我的实施:

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

int main(void)
{
    int ch;
    char *ptrChFromFile;
    char **ptrWords;
    int strSize = 1;
    int i;
    int j = 0;
    int k = 0;
    int numberOfWords = 1;

    ptrChFromFile = malloc(sizeof(char));

    if (ptrChFromFile == NULL)
    {
        puts("COULDN'T ALLOCATE MEMORY");
        exit(EXIT_FAILURE);
    }

    while ((ch = getchar()) != '\n')
    {
        ptrChFromFile = realloc(ptrChFromFile, (strSize+1) * sizeof(char));

        if (ptrChFromFile == NULL)
        {
            puts("failed to allocate memory");
            exit(EXIT_FAILURE);
        }

        if (ch == ' ')
        {
            numberOfWords++;
        }

        ptrChFromFile[strSize] = ch;
        strSize++;
    }

    ptrChFromFile[strSize] = 0;

    ptrWords = malloc(sizeof(char*) * numberOfWords); //creates number of slots in ptrWords

    for (i = 0; i < numberOfWords; i++) // allocates number of bytes in each slot.
    {
        ptrWords[i] = malloc(sizeof(char*)* strSize);
        if (ptrWords[i] == NULL)
        {
            puts("failed to allocate memory");
            exit(EXIT_FAILURE);
        }
    }

    if (ptrWords == NULL)
    {
        puts("failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < strSize; i++)
    {
        if (ptrChFromFile[i] != ' ')
        {
            ptrWords[j][k++] = ptrChFromFile[i];
        }
        else
        {
            ptrWords[j][k] = 0;
            ptrWords[j] = realloc(ptrWords[j], k+1);
            j++;
            k = 0;
        }
    }
    printf("%s", ptrWords[0]);

    free(ptrChFromFile);
    free(ptrWords);

    return 0;
}

样本输入:“嘿那里”

输出:嘿那里


当前版本的代码:

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


int getStrLength(char *word)
{
    int lengthOfWord = 0;
    int i;

    for (i = 0; word[i] != 0; i++)
    {
        lengthOfWord++;
    }
    return lengthOfWord;
}

int compareWords(char *firstWord, char *secondWord)
{
    while (*firstWord && *firstWord == *secondWord)
    {
        firstWord++;
        secondWord++;
    }
    return *firstWord - *secondWord;
}

int main(void)
{
    int ch;
    char *ptrChFromFile;
    char **ptrWords;
    char **ptrCrunchWord;
    int strSize = 0;
    int i;
    int j = 0;
    int k = 0;
    int numberOfWords = 0;
    int defaultWordLength = 6;

    srand(time(0)); // Use current time as seed for random generator

    ptrChFromFile = malloc(sizeof(char));

    if (ptrChFromFile == NULL)
    {
        puts("COULDN'T ALLOCATE MEMORY");
        exit(EXIT_FAILURE);
    }

    while ((ch = getchar()) != '\n') // this reads in chars from file to ch variable
    {
        ptrChFromFile = realloc(ptrChFromFile, (strSize+1) * sizeof(char));

        if (ptrChFromFile == NULL)
        {
            puts("failed to allocate memory");
            exit(EXIT_FAILURE);
        }

        if (ch == ' ')
        {
            numberOfWords++;
        }

        ptrChFromFile[strSize] = ch;
        strSize++;
    }

    numberOfWords++;
    ptrChFromFile[strSize] = 0;

    ptrWords = malloc(sizeof(char*) * numberOfWords); //creates number of slots in ptrWords

    if (ptrWords == NULL)
    {
        puts("failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < numberOfWords; i++) // allocates number of bytes in each slot.
    {
        ptrWords[i] = malloc(strSize);
        if (ptrWords[i] == NULL)
        {
            puts("failed to allocate memory");
            exit(EXIT_FAILURE);
        }
    }

    for (i = 0; i < strSize; i++) // This inserts words in ptrWords separated by spaces.
    {
        if (ptrChFromFile[i] != ' ')
        {
            ptrWords[j][k++] = ptrChFromFile[i];
        }
        else
        {
            ptrWords[j][k] = 0;
            ptrWords[j] = realloc(ptrWords[j], k+1);
            j++;
            k = 0;
        }
    }
    // terminate and resize last word
    ptrWords[j][k] = 0;
    ptrWords[j] = realloc(ptrWords[j], k+1);
    j = 0;
    k = 0;

    // crunchWord code starts here:
      ptrCrunchWord = malloc(sizeof(char*));
      ptrCrunchWord[0] = malloc(strSize);

      if (ptrCrunchWord == NULL || ptrCrunchWord[0] == NULL)
       {
           puts("failed to allocate memory");
           exit(EXIT_FAILURE);
       }


    for (i = 0; i < numberOfWords; i++)
    {
        int randomIndex = rand() % numberOfWords;

    if (compareWords(ptrCrunchWord[i], ptrWords[randomIndex]) != 0) 
    {
        if (getStrLength(ptrWords[randomIndex]) >= defaultWordLength) 
        {
            ptrCrunchWord[i] = ptrWords[randomIndex]; // main problem here
        }
    }
}

    printf("The crunch word is: %s", ptrCrunchWord[0]);


    for (i = 0; i < numberOfWords; i++) // Free's allocated memory from all pointers
    {
        free(ptrWords[i]);
    }

    free(ptrChFromFile);
    free(ptrWords);
    free(ptrCrunchWord[0]);
    free(ptrCrunchWord);

    return 0;
}

这是最新的代码。我需要做的最后一件事是在ptrCrunchWord中存储大于或等于6的所有单词。我的主要问题是在ptrCrunchWord [0]中为最终的紧缩字分配空间并将单词存储在索引0中。我只为元素分配空间,因为ptrCrunchWord中只存储一个单词。我写了两个方法,一个检查每个单词的长度,另一个方法比较两个单词,看看它们是否相同。最后,我需要打印没有空格的紧缩字。

谢谢

c tokenize dynamic-memory-allocation double-pointer
2个回答
1
投票

这个循环错了:

for (i = 0; i < strSize; i++)
{
    if (ptrChFromFile[i] != ' ')
    {
        ptrWords[j] = &ptrChFromFile[i];
    }
    else
    {
        ptrWords[j] = 0;
        j++;
    }
}

你不应该重新分配ptrWords[j],你应该复制到你在前一个循环中分配的内存中。您需要另一个变量k来保存您在目标数组中分配的索引。

int k = 0;
for (i = 0; i < strSize; i++)
{
    if (ptrChFromFile[i] != ' ')
    {
        ptrWords[j][k++] = ptrChFromFile[i];
    }
    else
    {
        ptrWords[j][k] = 0;
        j++;
        k = 0;
    }
}

你也为你分配给ptrWords的内存量过分了。每个单词都有与文件整个大小一样多的字符。到达每个单词的末尾后,在分配ptrWords[j][k] = 0之后,您可以将该分配缩小到单词的大小:

ptrWords[j] = realloc(ptrWords[j], k+1);

另一个问题是你初始化了strSize = 1;。这导致您将输入的第一个字符放入ptrChFromFile[1]而不是ptrChFromFile[0],因此第一个单词无法正确复制。它应该初始化为int strSize = 0。但是要调整此更改,您需要将所有ptrChFromFile分配增加1个字符(或者在末尾执行另一个realloc以为尾随空值添加空间)。

当你为ptrWords[i]分配内存时,你不应该乘以sizeof(char *)ptrWords是一个指针数组,ptrWords[i[char的数组。

完成读取ptrChFromFile初始输入的循环后,需要增加numberOfWords。否则你不会计算换行前的最后一个字。

你不应该在最后删除循环,释放所有ptrWords[i]。你用malloc分配的任何东西都需要被释放。

这是工作版本:

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

int main(void)
{
    int ch;
    char *ptrChFromFile;
    char **ptrWords;
    int strSize = 0;
    int i;
    int j = 0;
    int k = 0;
    int numberOfWords = 1;

    ptrChFromFile = malloc(2);

    if (ptrChFromFile == NULL)
    {
        puts("COULDN'T ALLOCATE MEMORY");
        exit(EXIT_FAILURE);
    }

    while ((ch = getchar()) != '\n')
    {
        ptrChFromFile = realloc(ptrChFromFile, (strSize+2));

        if (ptrChFromFile == NULL)
        {
            puts("failed to allocate memory");
            exit(EXIT_FAILURE);
        }

        if (ch == ' ')
        {
            numberOfWords++;
        }

        ptrChFromFile[strSize] = ch;
        strSize++;
    }
    numberOfWords++; // increment for last word

    ptrChFromFile[strSize] = 0;

    ptrWords = malloc(sizeof(char*) * numberOfWords); //creates number of slots in ptrWords

    for (i = 0; i < numberOfWords; i++) // allocates number of bytes in each slot.
    {
        ptrWords[i] = malloc(strSize);
        if (ptrWords[i] == NULL)
        {
            puts("failed to allocate memory");
            exit(EXIT_FAILURE);
        }
    }

    if (ptrWords == NULL)
    {
        puts("failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < strSize; i++)
    {
        if (ptrChFromFile[i] != ' ')
        {
            ptrWords[j][k++] = ptrChFromFile[i];
        }
        else
        {
            ptrWords[j][k] = 0;
            ptrWords[j] = realloc(ptrWords[j], k+1);
            j++;
            k = 0;
        }
    }
    printf("%s\n", ptrWords[0]);

    for (i = 0; i < strSize; i++) {
        free(ptrWords[i]);
    }
    free(ptrChFromFile);
    free(ptrWords);

    return 0;
}

0
投票

我将尝试显示更像您的初始版本的版本。

我将跳过阅读文件的部分。当然,需要应用与Barmar提到的strSize相关的修复。此代码在读取文件后开始。

    ptrChFromFile[strSize] = 0;

    ptrWords = malloc(sizeof(char*) * numberOfWords); //creates number of slots in ptr

    if (ptrWords == NULL)
    {
        puts("failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    #define MIN_LENGTH 6
    int start = 0, end = 0;
    numWords = 0; // Start counting again. Only handle words long enough.
    for (i = 0; i < strSize; i++) // Walk the inital array again
    {
        if (ptrChFromFile[i] == ` `)
        {
          end = i;
          if (end - start >= MIN_LENGTH)
          { // Found a word? Store address and terminate.
            ptrWords = &ptrChFromFile[start];
            ptrChFromFile[i] = 0;
            numWords ++;
          }
          // Words that are too short are ignored
          // Also if a second space follows, no new word is counted...

          // Prepare for new word starting at next position.
          start = end = i+1;
        }
    }

    // Maybe one more word without a space afterwards?
    end = i;
    if (end - start >= MIN_LENGTH)
    { // Found a word? Store address and terminate.
      ptrWords = &ptrChFromFile[start];
      // ptrChFromFile[i] = 0; This word is already terminated.
      numWords ++;
    }

    ptrWords = realloc(sizeof(char*) * numberOfWords); // Reduce size to only hold long words

    // Decide number n how many words shall be concatenated
    // Use scanf or any other mechanism...
    int n = numWords / 2; 

为了选择单词,我将使用数组来仅保存每个单词的索引。它用索引0..n-1初始化。对于每个选定的单词,我将索引移动到数组中的第一个位置,并将(前)第一个元素放到所选位置。在此之后,前n个元素保持随机索引值。随着每个步骤中随机选择的范围减小,不可能存在重复。不需要比较单词。

    // Create an array to hold the indices of chosen words.
    int selectedWords[n];
    for (i = 0; i < n; i++)
      selectedWords[i] = i;

    // Select n words, store index.
    srand(time(0));
    for (i = 0; i < n; i++)
    {     
      // Pick random element 0..n
      int elem = rand()%(n-i);
      int temp;
      temp = selectedWords[i+elem];
      selectedWords[i+elem] = selectedWords[i];
      selectedWords[i] = temp;
    }
    // This first n entries hold the selected words.

    // How long will it be in the end?
    size_t len = 0;
    for (i = 0; i < n; i++)
    {
      len += strlen(ptrWords[selectedWords[n]]);     
    }

    // Get memory for final result...
    char *resultWord = malloc(len+1);
    // TODO: check for NULL
    resultWord[0] = 0;

    for (i = 0; i < n; i++)
    {
      strcat(resultWord, ptrWords[selectedWords[n]]);     
    }
    printf("%s\n", resultWord)

    free(ptrChFromFile);
    free(ptrWords);
    free(resultWord);

    return 0;
}

代码未编译或测试。

© www.soinside.com 2019 - 2024. All rights reserved.