为什么我的代码不能读取 'for' 中的所有字符串?
Why won't my code read all the character strings in a 'for'?
如果我 运行 这段代码并为 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 后留在输入中的 '\n'
。
您可以将 scanf 更改为:scanf("%d\n", &n);
或在其后添加 getchar();
。
此外,如评论中所述,您在每个数组中分配了一个字符。您应该将结果 sizeof
乘以您想要的字母数 + 1(记住 [=15=]
。)
*(x + i) = (char*)malloc(sizeof(char) * DESIRED_LENGTH);
最后...你还应该释放所有指针(在释放 x 之前),否则你会发生内存泄漏:
for (int i = 0; i < n; i++)
free(*(x + i));
如果我 运行 这段代码并为 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 后留在输入中的 '\n'
。
您可以将 scanf 更改为:scanf("%d\n", &n);
或在其后添加 getchar();
。
此外,如评论中所述,您在每个数组中分配了一个字符。您应该将结果 sizeof
乘以您想要的字母数 + 1(记住 [=15=]
。)
*(x + i) = (char*)malloc(sizeof(char) * DESIRED_LENGTH);
最后...你还应该释放所有指针(在释放 x 之前),否则你会发生内存泄漏:
for (int i = 0; i < n; i++)
free(*(x + i));