我正在学习如何在C中使用指针(使用malloc和free),并且在此练习中遇到了一些麻烦。我只想创建一个指针数组,即可保存每个单词的方向。然后我想对一个特定的单词做一个free(),但是这个free使我的程序崩溃。
int main
{
printf("Introduce how many words do you want. \n");
scanf("%d", &numWords);
getchar();
char ***array = (char***)malloc(sizeof(char**) * numWords);
if (array == nullptr)
{
exit(1);
}
for (int i = 0; i < numWords; i++) array[i] = (char**)malloc(sizeof(char*)) ;
for (int i = 0; i < numWords; i++)
{
printf("Enter your word number %d: \n", i + 1);
scanf("%s", &(array[i]));
getchar();
}
for (int i = 0; i < numWords; i++)
{
printf("%s \n", &(array[i]));
}
free(array[1]);
printWord(array[2])
}
另外,我要执行此功能,因为我想在单词的每个字符之前打印一个空格。它也使我的程序崩溃。
void printWord(char **array)
{
for (int i = 0; i < strlen(*array); i++) printf("%c ", &((*array)[i]));
}
不知道该如何集中精力。您向我推荐什么?您在我的代码中发现任何问题吗?谢谢你。
您需要char**
解决很多问题和错误,这些问题和错误应该得到解决:
int main{}
应该至少int main(void){}
你需要(void)
scanf
错误nullptr
这是c++
关键字,应该是NULL
free
您的malloc
饮食方式。casting
malloc并不总是一个好主意,请阅读此内容您的代码应如下所示:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
long unsigned int numWords,i;
char **array;
printf("Introduce how many words do you want:> ");
if((scanf("%lu", &numWords)) != 1){
printf("Error, Fix it!\n");
exit(1);
}
array = malloc(sizeof(char*) * numWords * numWords);
if (array == NULL) {
exit(2);
}
for (i = 0; i < numWords; i++){
array[i] = malloc(sizeof(char*) * 100);
}
for (i = 0; i < numWords; i++){
printf("Enter your word number %lu:> ", i + 1);
if((scanf("%s", array[i])) != 1){
printf("Error, Fix it!\n");
exit(3);
}
}
for (i = 0; i < numWords; i++){
printf("%s \n", array[i]);
}
for (i = 0; i < numWords; i++){
free(array[i]);
}
free(array);
return 0;
}
输出:
Introduce how many words do you want:> 3
Enter your word number 1:> Michi
Enter your word number 2:> aloha
Enter your word number 3:> cool
Michi
aloha
cool
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句