Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

c++ - Why won't my code read all the character strings in a 'for'?

If i run this code and choose 3 for n (the number of sentences read from the keyboard), it will allow me to only read two of them. What am i doing wrong?


#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,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
", *(x + i));
    }
    free(x);
}
question from:https://stackoverflow.com/questions/65649434/why-wont-my-code-read-all-the-character-strings-in-a-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are forgetting to take the ' ' that was left in the input after you read n.

You can either change your scanf to: scanf("%d ", &n); or add a getchar(); right after it.

Also, as mentioned in comments, you are allocating a single char in each array. You should multiply the result sizeof by the number of letters you want + 1 (remember the .)

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

And at the end... you should also free all the pointers (before freeing x), other wise you would have a memory leak:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...