2

Right, this is (the last) assignment for my C introduction web class.

The assignment presents the main program, does not explain anything about it and tells you to write a function to print and sum the array in it.

However I don't really understand what is going on in the main program.

Translated for your convenience;

Source code:

#include <stdio.h>
#include <stlib.h>

void print_count(int *, int);

int main(int argc, char *argv[]) {
    int x, sum = 0, size = 0, array[5];
    if (argc == 6) {
        /* Program name and parameters received from command line */
        for (x = 0; x < argc - 1; x++) {
            array[x] = atoi(argv[x + 1]);
        }
        print_count(array, size);
    } else {
        printf("Error\n");
    }
    return 0;
}       

Now I am completely clueless as to how to start writing the program requested and what variables to call/how to write the function.

Edit3: completed exercise

void print_count(int *array, int size) {
    int i;
    int sum = 0;

    printf("Elements: ");
    for (i = 0; i <= size; i++) {
        printf("%d ", (array[i]);
        sum = sum += array[i]);
    }
    printf("\nSum = %d ", sum);

    return 0;
}

I would like to understand what is going on in the main program and preferably come to an answer on how to actually write the function by myself.

7
  • This array[5] = atoi(... had been give to you exactly this way? Commented Jun 22, 2017 at 9:48
  • well first off, array[5] = atoi(argv[x+1]); is totally wrong. array is only defined as having 5 elements, not 6 (it starts at 0) and you probably want that to be array[x] so you get all the values. Commented Jun 22, 2017 at 9:48
  • When you write code for print_count you need to provide names for the two input variables. You can then use those names to access the variables. For example void print_count(int *arr, int size) {. Commented Jun 22, 2017 at 10:00
  • Am I the only one disturbed by the for loop in the lesson's code? int i; int count=argc-1; char ** values = &argv[1]; for (i=0; i<count; i++){arrray[i]=atoi(values[i]);} would be cleaner. I thought lessons are meant to teach good practice? Commented Jun 22, 2017 at 14:19
  • The posted code does not compile! The main problem is there is no header file named: stlib.h. Perhaps the OP made a slight error and the name should be: stdlib.h Commented Jun 23, 2017 at 0:38

3 Answers 3

3

This:

array[5] = atoi(argv[x+1]);

is clearly wrong, it always tries to assign to array[5] which is out of bounds. It should be:

array[x] = atoi(argv[x + 1]);

This converts the x + 1:th argument from string format into an integer, and stores that in array[x]. If you're not familiar with the standard function atoi(), just read the manual page.

So if you start the program like this:

./myprogram 1 2 3 4 5

That has 6 arguments (the first is the name itself), and will end up with array containing the numbers one through five.

Then in the summing function, the first line should be something like:

void print_count(int *array, int size)

so that you give names to the arguments, which makes them usable in the function. Not providing names is an error, I think.

And it doesn't need to "interact" with main() more than it already does; main() calls print_count(), passing it a pointer to the first element of array and the length of the array, that's all that's needed to compute the sum.

Sign up to request clarification or add additional context in comments.

2 Comments

oh crap, yeah, lost a detail when rewriting the code while translating, sorry! editing the source code now.
Thank you! it would have taken me far too long to figure out what variables to call with the function (I had no idea you can leave them undeclared in the prototype), after that and a short moment to myself spent facepalming, I completed the exercise. and (after an additional while spent googling) I think I now have a general idea of what the atoi and argv arguments do.
1

Your print_count function has a few issues:

  • The loop runs one step too far: i should vary between 0 and size-1 included. The standard idiom for this loop is:

       for (i = 0; i < size; i++) {
           ...
    
  • Incrementing sum is simply done with:

    sum += array[i];
    
  • There is an extra ( on the first printf line.

  • You should print a newline after the output.
  • Returning 0 from a void function is invalid.

Here is a corrected version:

void print_count(int *array, int size) {
    int i;
    int sum = 0;

    printf("Elements: ");
    for (i = 0; i < size; i++) {
        printf("%d ", array[i]);
        sum += array[i]);
    }
    printf("\nSum = %d\n", sum);
}

2 Comments

the question was not about the OPs function: print_count() but rather the OP needs help understanding the main() function.
@user3629249: indeed his question was addressed in other answers. My post pertains to the OP's Edit3: completed exercise. I'm afraid the exercice is not really complete with the posted code for the print_count function.
1

the following proposed code:

  1. cleanly compiles.
  2. explains what is being accomplished at each step of the 'main()' function.
  3. properly outputs error messages to 'stderr'.
  4. implements the typical method to announce an error in the number of command line parameters.

Now the proposed code with explanatory comments:

#include <stdio.h>    // printf(), fprintf()
#include <stdlib.h>   // atoi(), exit(), EXIT_FAILURE


void print_count(int *, int);

int main(int argc, char *argv[])
{
    if (argc != 6)
    {
        fprintf( stderr, "USAGE: %s int1 int2 int3 int4 int5\n", argv[0] );
        exit( EXIT_FAILURE );
    }

    // implied else, correct number of arguments

    // only declare variables when they are needed
    int array[5];

    // place each command line parameter into 'array', 
    // except program name
    // I.E. skip the program name in argv[0]
    for( int i = 1; i < argc;  i++ )
    {
        // array[] index starts at 0, but loop counter starts at 1
        array[i-1] = atoi(argv[i]);
    } // end for( each value pointed at by argv[], except program name )

    // print sum of command line parameters to stdout
    int size = argc-1;  // number of command line parameters after program name
    print_count(array, size);
    return 0;
} // end function: main

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.