pass the sum by pointer, generates output error

0

I have the following simple code in C:

void main()
{
    int* s;
    int a = 5, b = 3;
    sum(a, b, s);
    printf("%d + %d = %d", a, b, *s);
}
void sum(int a, int b, int* s) {
    *s = a + b;
}

the program compiles, but gives a runtime error. Why?

Process returned -1073741819 (0xC0000005) execution time : 0.972 s Press any key to continue.

c
asked on Stack Overflow Sep 27, 2020 by Serge • edited Sep 27, 2020 by Serge

3 Answers

2

First of all, avoid implicit function declaration

#include <stdio.h>

void sum(int a, int b, int* s);

void main()
{
    int s;
    int a = 5, b = 3;
    sum(a, b, &s);
    printf("%d + %d = %d", a, b, s);
}

void sum(int a, int b, int* s) {
    *s = a + b;
    return;
}

This prints 8. If you still wish to use int* s then allocate space for a single int.

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

void sum(int a, int b, int* s);

void main()
{
    int* s = malloc(sizeof(int)*1);
    int a = 5, b = 3;
    sum(a, b, s);
    printf("%d + %d = %d", a, b, *s);
}

This will also print 8.

answered on Stack Overflow Sep 27, 2020 by Tony Tannous • edited Sep 27, 2020 by Tony Tannous
1

s is an int* which means that it can store the address of an int. However, you never made it do so. Therefore, when sum dereferences it, you're dereferencing an invalid address (i.e., whatever junk stack data s was assigned when main began).

You need to do something like

int main() {
    int a, b, c;

    a=5;
    b=3;

    sum(a,b,&c);
    printf("%d + %d = %d", a, b, c);

    return 0;
}

Or, if you want to use an int* variable,

int main() {
    int *s;
    int a, b, c;

    a=5;
    b=3;
    s=&c;

    sum(a,b,s);
    printf("%d + %d = %d", a, b, *s);

    return 0;
}
answered on Stack Overflow Sep 27, 2020 by Daniel Walker
1
int* s;

Here you're creating a pointer to int. But if you haven't located any memory for the int yet.

A possible solution would be to declare the same way you did with a and b, and then pass its reference to the function.

void main()
{
    int s;
    int a = 5, b = 3;
    sum(a, b, &s);
    printf("%d + %d = %d", a, b, s);
}
void sum(int a, int b, int* s) {
    *s = a + b;
}
answered on Stack Overflow Sep 27, 2020 by 89f3a1c

User contributions licensed under CC BY-SA 3.0