The Gateway to Computer Science Excellence
0 votes

int main(void)
    int maxLineCount = 500, maxCharCount = 500, index, j, count;
    char *line = NULL;
    size_t size;

char *a[maxLineCount];
    for (index = 0; index < maxLineCount; index++)
        a[index] = (char *)malloc(maxCharCount * sizeof(char));
int noOfLine = 0;
    // read the input as line
    while(getline(&line, &size, stdin) != -1) {
    for(index = 0; index < noOfLine; index++)
    printf("%s", a[index]);
    return 0;

Can anyone please explain what each line of the code is doing.

suppose we have 3 string given as input in 3 different lines then how can we access each character of the string?

in Programming by Boss (24.1k points) | 234 views
not getting code clearly.

Is it copying string , which are dynamically given and then printing those string??
Yes it is taking input of multiple strings , where each string is written in a seperate line and then it is printing those strings.

1 Answer

+1 vote

Use following snippet of code to get each character one by one

for(int i=0; i<noOfLine; i++){
    for(int j=0; a[i][j]!='\0'; j++)
        printf("%c", a[i][j]);

instead of

for(index = 0; index < noOfLine; index++)
    printf("%s", a[index]);

From my snippet you can understand that pointer of array are no differ than 2-d array when allocating a fix amount of memory whether at compile time or at run time. 

You could have used malloc function after getting number of string and finding length of each string. So that memory can be allocate accordingly to save memory at runtime.


In your case we have to allocate 500*500 memory blocks, which doesn't look good. If you are using malloc function, then use it to assign optimal amount of memory.


If you found an error, feel free to point out.

by (59 points)
I have not written the code ...I wanted to know what each line of the code is doing. How the memory is being allocated.

Then use "Debug" property of IDE.  Using breakpoint try to debug this program, you will find it interesting as you will came to know what is the flow of your code.


just reduce maxLineCount & maxCharCount to

maxLineCount = 5, maxCharCount = 5

So that it takes min time.

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,332 answers
105,197 users