c语言 - 我很难使用指针和动态数组



编辑:感谢所有的反馈!我已经为strlen更改了尺寸,谢谢你指出。至于c++代码,这里有一个tl;博士。我们应该学习纯C,但教授在他的讲座和笔记中有C++代码。所以,除非它非常明显(比如std::vector(,否则我可以使用一些C++函数。我还看到有人提到内存泄漏,我该怎么解决?编辑2:有人提到使用new[]而不是malloc,还有人说我的第二个malloc应该有另一个free((。我可以简单地将其更改为新[]吗?它还会是一个动态数组吗?我在笔记中似乎找不到新的[],所以我搜索了一下,但我只需要确认这就是我要做的。由于有人的洞察力,我还更改了2行有问题的行。非常感谢。

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

#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("%ct", a_answer[i]);
guessWord[i] = convertChar(a_answer[i], numLowerCase);
printf("%ct", guessWord[i]);
}
return guessWord;
}

我99%确信问题出在"char*a_clul=(char*(malloc(sizeof(aWord((;a_clux=wheelOfFortune(aWord

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

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

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

您首先分配一块内存来分配给指针。然后立即将该指针分配给wheelOfFortune()返回的任何值。您无法访问已分配内存的原始块。你应该把它改成

char* a_clue = wheelOfFortune(aWord);

最新更新