簡體   English   中英

為什么我的代碼不能讀取“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 (記住\0 。)

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

最后......您還應該釋放所有指針(在釋放 x 之前),否則您將有 memory 泄漏:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM