The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
0 votes
104 views
#include<stdio.h>
#include<stdlib.h>

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) {
        strcpy(a[noOfLine++],line);
    }
    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?

asked in Programming by Boss (16.2k points) | 104 views
0
not getting code clearly.

Is it copying string , which are dynamically given and then printing those string??
0
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.

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

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.

Related questions

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
49,811 questions
54,528 answers
188,403 comments
75,479 users