【发布时间】:2021-04-15 08:48:41
【问题描述】:
如果我运行此代码并为 n(从键盘读取的句子数)选择 3,它将只允许我阅读其中两个。我做错了什么?
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
#define MAX 20
int main()
{
int n;
printf("Enter the number of sentences: ");
scanf("%d", &n);
char** x = (char**)malloc(n * sizeof(char*));
for (int i = 0; i < n; i++)
*(x + i) = (char*)malloc(sizeof(char));
printf("Enter %d sentences of a maximum of %d characters:\n",n,MAX);
char msj[MAX]="";
for (int i = 0; i < n; i++)
{
cin.getline(msj, MAX);
strcpy(*(x + i), msj);
}
printf("The sentences are:");
for (int i = 0; i < n; i++)
{
printf("%s\n", *(x + i));
}
free(x);
}
【问题讨论】:
-
你正确分配了n个指针,但每个句子只分配1个字符的内存。
-
您为什么使用
malloc、scanf或free?如果您想使用这些函数,请编写 C。如果您想用 C++ 编写,请不要使用其中任何一个。 -
这段代码是 C。虽然简单地添加
<iostream>和using namespace std,但需要将代码编译为 C++,这与 C++ 的实际编写方式相差甚远,或者至少应该是写的。
标签: c++ string pointers char scanf