【问题标题】:I'm having a hard time with pointers and dynamic arrays我很难使用指针和动态数组
【发布时间】:2019-11-19 16:53:58
【问题描述】:

编辑:感谢所有反馈!我已经更改了 strlen 的 sizeof,感谢您指出。至于 c++ 代码,这里有一个 tl;dr.我们假设学习纯 C,但教授在他的讲座和笔记中有 C++ 代码。因此,除非它非常明显(如 std::vector),否则我可以使用一些 C++ 函数。我还看到有人提到内存泄漏,我该如何解决? 编辑 2:有人提到使用 new[] 而不是 malloc 和另一个我应该为我的第二个 malloc 使用另一个 free()。我可以简单地将其更改为 new[] 吗?它仍然是一个动态数组吗?我似乎无法在我的笔记中找到 new[] 所以我搜索它,但我只需要确认这是我正在尝试做的事情。由于某人的洞察力,我还更改了两条有问题的行。非常感谢。

上下文:这是为大学做的一项小任务。我正在尝试获取一个单词作为输入(例如“Hello World!”),然后将其转换为删除辅音(例如“_e__o _o___!”)。在交换数组中的字母时,现在一切都很好。当我尝试将其合并到主要功能中时,问题就来了。函数“wheelOfFortune”完成了它的工作,但它似乎没有将值传递给 a_clue。代码如下:

#include <stdio.h>   
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <assert.h>

//prototypes
char* wheelOfFortune(char* a_answer);
//This checks if the letter is a consonant. If it is, it replaces it with '_'
char convertChar(char letter, int isLowerCase);
//this was done for learning purposes. It simply identifies whether the letter is upper or lower case
int isLowerCase(char letter);

int main()
{
/*aWord should be a user input, but it's easier in terms of debugging if I put I automatically gave it values*/
char aWord[15];
    for (int i = 0; i < strlen(aWord); i++)
    {
        aWord[i] = 'a' + (i / 3);
    }
    for (int k = 0; k < strlen(aWord); k++)
    {
        printf_s("%c", aWord[k]);
    }
    printf_s("\n");
    char* a_clue = wheelOfFortune(aWord); //This line has been edited
    printf_s("%s", a_clue);
    free(a_clue);
}

char* wheelOfFortune(char* a_answer)
{
    unsigned int numChar = strlen(a_answer);
    char* guessWord = (char*)malloc(strlen(a_answer));
    int numLowerCase = 0;
    for (int i = 0; i < 15; i++)
    {
        numLowerCase = isLowerCase(a_answer[i]);
        printf("%c\t", a_answer[i]);
        guessWord[i] = convertChar(a_answer[i], numLowerCase);
        printf("%c\t", guessWord[i]);
    }
    return guessWord;
}

我 99% 确定问题出在“char* a_clue = (char*)malloc(sizeof(aWord)); a_clue = wheelOfFortune(aWord);”这行代码上。但我不知道该怎么做。

【问题讨论】:

  • sizeof(a_answer) 并没有像您认为的那样做。提示:strlen()。为什么你认为sizeof 与这里相关?编辑:我猜是因为它确实适用于实际数组,而不是指针。
  • unsigned int numChar = sizeof(a_answer),只会是指针的大小,而不是字符数。试试strlen,或者传入数组的大小。
  • 改用std::vector 可以省去很多麻烦。
  • malloc -- 如果要在 C++ 中进行手动内存管理,请使用 new[] 而不是 malloc。此外,我知道没有 C++ 书籍显示使用 malloc(可能是 new[],但不是 malloc)。您是在阅读 C 书籍和资料而不是 C++?
  • char* a_clue = (char*)malloc(sizeof(aWord));a_clue = wheelOfFortune(aWord); -- 内存泄漏。

标签: c pointers memory-management


【解决方案1】:

我还看到有人提到内存泄漏,我该如何解决?

一般的经验法则是每个malloc() 都必须有一个对应的free()。我在您的代码中看到两个malloc() 调用,但只有一个free()。仔细检查会发现导致内存泄漏的这两行代码:

char* a_clue = (char*)malloc(sizeof(aWord));
a_clue = wheelOfFortune(aWord);

你首先分配一块内存来分配给一个指针。然后您立即将该指针指定为指向wheelOfFortune() 返回的任何内容。您无法访问原始分配的内存块。您应该将其更改为

char* a_clue = wheelOfFortune(aWord);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2021-12-19
    相关资源
    最近更新 更多