我很难使用指针和动态数组

问题描述 投票:-1回答:1

编辑:感谢您的所有反馈!我已将sizeof更改为strlen,感谢您指出。至于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 = (char*)malloc(strlen(aWord));
    a_clue = wheelOfFortune(aWord);
    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);”行中但我不知道该如何解决。

c++ c
1个回答
0
投票

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

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

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

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

char* a_clue = wheelOfFortune(aWord);
© www.soinside.com 2019 - 2024. All rights reserved.