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.
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.
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;
}
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;
}
User contributions licensed under CC BY-SA 3.0