简体   繁体   中英

calculating the sum of input numbers in c language

I want to calculate the sum of input numbers using pointer concept in c language.But when i compile the given below program correct value for sum does not appear. help me to find the mistake i have done in the below program.

#include<stdio.h>

void main()
{   
    int g , *p;

    int sum = 0;

    int x=1;

    for(int i=1; i<3; i++ )
    {   
        scanf("%d ", &g);       
    }

        p = &g;

    while( x < 3){
    sum =  sum + *p;
    p++;
    x++;
    }

    printf("\n sum = %d ",sum);

}

Your g is only one integer so:

  1. Each time you call scanf("%d ", &g); , you will overwrite the previous value.
  2. When you increment the pointer in p++; , that pointer will no longer be valid. (Where do you think it will point to?)

If you want to store three different values in g , you need to make it an array of integers.

To do this, make the following changes to your code:

int g[3] , *p; // "g" can now store three different values
int x=0; // Later on - counting from 0 thru 2 in the "while" loop
//...
for (int i=0; i<3; i++) // NOTE: Arrays begin at "0" in C!
{   
    scanf("%d ", &g[i]); // Store to the element indexed by "i"       
}
//...
p = g; // For arrays, don't need the & operator: this will give address of first element

You can store only one number in g .

Therefore, p++; here will make p point at an invalid place.

You should allocate an array to store all input values.

Also note that you should use standard int main(void) in hosted environment instead of void main() , which is illegal in C89 and implementation-defined in C99 or later, unless you have some special reason to use non-standard signature.

#include<stdio.h>

int main(void)
{   
    int g[3] , *p;

    int sum = 0;

    int x=1;

    for(int i=1; i<3; i++ )
    {   
        scanf("%d ", &g[i]);
    }

        p = &g[1];

    while( x < 3){
    sum =  sum + *p;
    p++;
    x++;
    }

    printf("\n sum = %d ",sum);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM