1

I am trying to implement bubble sort in C. The question has a constraint that:

  1. The first line should be the number of elements in the array

  2. The second line is the input

For example:

first line: 5
second line: 5 4 2 8 1

I need to read the second line an storing it into an array to be able to sort them. I have searched on the internet and found that getline() helps us to read a line. The issue here is that if I want to use getline() I need to know how many bits are going to read so I can allocate enough space for it, but here we do not know how along a number would be. The code I have written is as follow:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char ** argv){
    int sizeOfArray;
    // getting the number of inputs from the second line.
    // Then go to the third line
    scanf("[^\n]%d[^\n]", &sizeOfArray);
    int inputArray[sizeOfArray];
    //------------------------------------
    // This bit I have stuck. I do not know how to solve it
    for(int iteration = 0; iteration<sizeOfArray; iteration++)
    {
        ("%d ", &inputArray[iteration]);
    }
    // ----------------------------
    int arrSizeCopy = sizeOfArray;
    int mediator = 0 ; 
    while(arrSizeCopy> 0)
    {
        for(int i=0; i< arrSizeCopy-1; i++)
        {
            if(inputArray[i]>inputArray[i+1])
            {
                mediator = inputArray[i];
                inputArray[i] = inputArray[i+1];
                inputArray[i+1] = mediator;
            }
        }
        arrSizeCopy--;
    }
    for (int i=0; i<sizeOfArray; i++)
    {
        printf("%d ", inputArray[i]);
    }
return 0;
}

I really appreciate if someone could help me to find the answer for it.

vinayawsm
  • 845
  • 9
  • 28
Hossein
  • 107
  • 1
  • 10
  • Welcome to Stack Overflow. Please read the [About] and [Ask] pages soon. Please do **NOT** include line numbers in your code — it makes it hell to copy'n'paste if we need to compile it to see what's going wrong. – Jonathan Leffler Nov 03 '18 at 00:02
  • Note that `scanf()` doesn't care about newlines at all except to the extent that they are white space separating numbers (like blanks and tabs are). Therefore, if you don't have to validate the input (and code contest sites usually don't require that), then you could simply read the count and then read that many numbers, and it won't matter whether they're all on a single line or not. – Jonathan Leffler Nov 03 '18 at 00:05
  • If you do decide to read the line of numbers into a string, then you probably need to know about [using `sscanf()` in a loop](https://stackoverflow.com/questions/3975236/how-to-use-sscanf-in-loops) or [correct usage of `strtol()`](https://stackoverflow.com/questions/14176123/correct-usage-of-strtol) — either can be used to step through a string converting integers one at a time. – Jonathan Leffler Nov 03 '18 at 00:11

2 Answers2

2

this is from the getline man page, and it looks to answer your concerns

   "If *lineptr is set to NULL and *n is set 0 before the call, then
   getline() will allocate a buffer for storing the line.  This buffer
   should be freed by the user program even if getline() failed.

   Alternatively, before calling getline(), *lineptr can contain a
   pointer to a malloc(3)-allocated buffer *n bytes in size.  If the
   buffer is not large enough to hold the line, getline() resizes it
   with realloc(3), updating *lineptr and *n as necessary."  

http://man7.org/linux/man-pages/man3/getline.3.html

newbie
  • 558
  • 7
  • 12
0

This line

scanf("[^\n]%d[^\n]", &sizeOfArray);

seems a bit strange.

So I changed your code like

 if (scanf("[^\n]%d[^\n]", &sizeOfArray) != 1)
 {
    printf("Bad luck\n");
    return;
 }

and gave it the input you describe, i.e. 5. The result was Bad luck So the scanf failed and sizeOfArray is uninitialized (which is very bad).

Instead simply try

 if (scanf("%d", &sizeOfArray) != 1)
 {
    printf("Bad luck\n");
    exit(1);
 }

and you'll see it work.

Also change

scanf("%d ", &inputArray[iteration]);

into

if (scanf("%d", &inputArray[iteration]) != 1)
{
    printf("Bad luck\n");
    exit(1);
}

When using scanf you shall always check the return value.

A complete example for reading and printing data:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char ** argv)
{
    int sizeOfArray;
    if (scanf("%d", &sizeOfArray) != 1)
    {
        printf("Bad luck\n");
        exit(1);
    }

    int inputArray[sizeOfArray];
    for(int iteration = 0; iteration<sizeOfArray; iteration++)
    {
        if (scanf("%d", &inputArray[iteration]) != 1)
        {
            printf("Bad luck\n");
            exit(1);
        }
    }

    for (int i=0; i<sizeOfArray; i++)
    {
        printf("%d ", inputArray[i]);
    }

    return 0;
}

Input:

5
1 2 3 4 5

Output:

1 2 3 4 5
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • the issue is that the compiler does not allow me to insert my element after defining the size of the array it gets terminated. – Hossein Nov 03 '18 at 00:26
  • Basically, when I execute the file, it waits so the user insert the size of the array. When the user inserts the size and hit the enter, the cursor should point to the next line and wait for the user to insert the elements in the array. The issue is that as soon as the user put the fist input and press enter, the programme terminates without waiting for the user to insert the array elements. – Hossein Nov 03 '18 at 00:33
  • @Hossein I'm not sure what you mean by that but you can see a working example here: https://ideone.com/ZO2LNp – Support Ukraine Nov 03 '18 at 00:33
  • @Hossein Is that happening after making the changes I suggest? – Support Ukraine Nov 03 '18 at 00:33
  • Yes, I implemented your suggestion but still it appears not to be working. – Hossein Nov 03 '18 at 00:35
  • @Hossein I added a complete example - try that. – Support Ukraine Nov 03 '18 at 00:40