【问题标题】:Why won't my code read all the character strings in a 'for'?为什么我的代码不能读取“for”中的所有字符串?
【发布时间】: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个字符的内存。
  • 您为什么使用mallocscanffree?如果您想使用这些函数,请编写 C。如果您想用 C++ 编写,请不要使用其中任何一个。
  • 这段代码是 C。虽然简单地添加 &lt;iostream&gt;using namespace std,但需要将代码编译为 C++,这与 C++ 的实际编写方式相差甚远,或者至少应该是写的。

标签: c++ string pointers char scanf


【解决方案1】:

您忘记了读取 n 后留在输入中的'\n'

您可以将您的 scanf 更改为:scanf("%d\n", &amp;n); 或在其后添加 getchar();

此外,如 cmets 中所述,您在每个数组中分配一个字符。您应该将结果 sizeof 乘以您想要的字母数 + 1(记住 \0。)

*(x + i) = (char*)malloc(sizeof(char) * DESIRED_LENGTH);

最后...你还应该释放所有指针(在释放 x 之前),否则你会出现内存泄漏:

for (int i = 0; i < n; i++)
   free(*(x + i));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    相关资源
    最近更新 更多