I'm trying to sum command-line integers. My total is constantly 473. I dont know how to get the right total.

#include <stdio.h>
     4  #include <stdlib.h>
     5  #include <ctype.h>
     6
     7  #define MAX 100
     8
     9  void sum(char *a, int n);
    10
    11  main (int argc, char *argv[])
    12  {
    13     int i;
    14     char *holder[MAX];
    15
    16
    17     for(i=0; i<argc; i++)
    18      {
    19        atoi(argv[i]);
              *argv=*holder;
    20      }
    21
    22     
 23
    24      sum(*holder,MAX);
    25  
    26      return 0;
    27  }
    28  
    29  void sum(char *a, int n)
    30  {
    31       int i;
    32       int f=0;
    33  
    34       for (i=0; i<n; i++)
    35            f+=a[i];
    36  
    37       printf("Total: %d\n", f);
    38  }

You have this

atoi(argv);

Which doesn't save the value generated by the function atoi()

Here's the definition of atoi

int atoi(const char *nptr);

Note it returns an integer and does not change the value of nptr in place.

I have since changed the whole thing. That was a big help. Now I can't get the total to come out right. It says 3 every time. Also, I'm supposed to be able to type in the command line sum and then numbers and its supposed to work. Am I not allowed to put a=atoi(argv)? I don't know how else to put the value into an array. Here is my new code.


3  #include <stdio.h>
     4  #include <stdlib.h>
     5  #include <ctype.h>
     6
     7  #define MAX 100
     8
     9  main (int argc, char *argv[])
    10  {
    11     int i, sum=0, j;
    12     int a[MAX];
    13   
    14     for (i=0; i< argc; i++)
    15         a[i]= atoi(argv[i]);
    16
    17
    18     for (j=0; j<MAX; j++);
    19        sum += a[j];
    20
    21      printf("Total: %d\n", sum);
    22
    23      return 0;

There are several mistakes in your code. I have corrected them and look out for the comments in the codes below:

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

#define MAX 100

int main(int argc, char *argv[])
{
	int i, j = 0, sum = 0;
	int a[MAX];

	// i start from 1 because argv[0] is application name
	for(i=1; i<argc; i++)
	{
		a[i-1] = atoi(argv[i]);		// store into buffer
		j++;						// increment counter
	}

	// cannot add up to MAX because unused buffer has undetermined values
	for(i=0; i<j; i++)
	{
		sum += a[i];		// add all values
	}

	printf("Total: %d\n", sum);

	return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.