6,138 views
6 votes
6 votes
#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?

1 Answer

4 votes
4 votes

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.

Related questions

0 votes
0 votes
1 answer
1
dixit bishwash asked Mar 31, 2018
1,173 views
The Correct answer is c but how?int main(){ int a=210,b=120,c; c=a>b?1,2,3:2,5,6,7; printf("%d",c);}ans:-a) 1b) 2c) 3d) Error.