2

I'm self-learning C and I came across a problem where lines need to be sorted according to their lengths. This portion stores characters from the input stream into an array and puts each lines in an array of pointers. Then tries to print the first line.

#include <stdio.h>
#include <string.h>
#define LINES 5
void main()
{
   char c;
   char* str1 = (char*)malloc(30);
   char* str[LINES];
   int i = 0,temp;
   while ((c = getchar()) != EOF) //storing all characters from input stream into an array
      *(str1 + i++) = c;
   *(str1 + i) = '\0';
   temp = i;//total number of characters
   i = 0;
   int j = 0, k = 0;
   str[j] = (char*)malloc(30);
   while (i < temp)//storing each line in separate pointers of the array of pointers
   {
      if (j + 1 == LINES)
         break;
      if (*(str1 + i) == '\n')
      {
         *(*(str + k) + j++) = '\0';
         str[j] = (char*) malloc(30);
         k = 0;
      }
      else
         *(*(str + k++) + j) = *(str1 + i);
      i++;
   }
   printf("%s\n", str[0]);//printing the first line

}

This is what my output screen looks like:

iiii
iii
ii
i
i
^Z
Press any key to continue . . .

In the input screen after giving the input and entering EOF the program crashes. Why is it not working?

btw it crashes after EOF.

Tormund Giantsbane
  • 355
  • 1
  • 4
  • 12

1 Answers1

1

The issue is that you have swaped the j and k indices.

*(*(str + k++) + j) = *(str1 + i);
*(*(str + k) + j++) = '\0';

is equivalent to:

str[k++][j] = str1[i];
str[k][j++] = '\0';

and it's not what you want to do. What you want is:

str[j][k++] = str1[i]; /* *(*(str + j) + k++) = *(str1 + i); */
str[j++][k] = '\0';    /* *(*(str + j++) + k) = '\0';        */

Other comments (some of them from the comments on you question):

  1. void main() should be int main(void)
  2. Compile using -Wall -Wextra, specially if you're learning
  3. your first while is a for:

    for (i = 0; (c = getchar()) != EOF) && i < temp-1; i++)
        *(str + i) = c;
    

    or

    for (i = 0; (str[i] = getchar()) != EOF) && i < temp-1; i++)
        ;
    
  4. your second while is also a for: for (i = 0, j = 0, k = 0; i < temp && j < LINES; i++)

  5. you'll miss the last line, because of that j + 1 == LINES.
  6. Unless you are practicing pointers, don't do this *(*(str + k++) + j); even if you are practicing pointers, don't do this as you can practice accessing with a pointer, instead of an index with pointer notation.
  7. read string.h documentation, you'll find plenty of functions to ease your life: fgets, strchr, strdup, etc.
Mance Rayder
  • 353
  • 2
  • 10