I have created a function that does the euclidean division in C and putting the quotient and remainder as function arguments.
code listing 1:
#include<stdio.h>
#include<stdlib.h>
void euclidean(int a, int b, int * q, int * r);
int main(int argc, char ** argv){
int * q;
int * r;
euclidean(5,4, q, r);
printf("q = %d, r = %d", *q, *r);
return 0;
}
void euclidean(int a, int b, int * q, int * r){
q = (int*)malloc(sizeof(int));
r = (int*)malloc(sizeof(int));
*q = a/b;
*r = a % b;
//printf("q = %d, r = %d", *q, *r); //this will show
return;
}
code listing 2:
#include<stdio.h>
#include<stdlib.h>
void euclidean(int a, int b, int * q, int * r);
int main(int argc, char ** argv){
int * q;
int * r;
euclidean(5,4, q, r);
printf("q = %d, r = %d", *q, *r);
return 0;
}
void euclidean(int a, int b, int * q, int * r)
{
*q = a / b;
*r = a % b;
//printf("q = %d, r = %d", *q, *r); //this won't show
return;
}
Both version aren't working. I compiled and ran the code on windows and the program is killed on runtime without printing anything (i.e. "q = 1, r = 4"). And my guess is if I had to compile and run it on linux, the terminal would gave me a "segmentation fault" error (not sure). I really don't see why it isn't working, especially with code listing 1. For code listing 2 one can argue that since the result of the operation are some sort of constant variable inside a function in which they were created, they could not be kept at the end of the function (I need confirmation on that too). Thanks
Keep It Simple, Stupid (there is such a principle).:)
#include<stdio.h>
#include<stdlib.h>
void euclidean(int a, int b, int * q, int * r);
int main(int argc, char ** argv){
int q;
int r;
euclidean(5,4, &q, &r);
printf("q = %d, r = %d", q, r);
return 0;
}
void euclidean(int a, int b, int * q, int * r)
{
*q = a / b;
*r = a % b;
}
If you want indeed to allocate memory in the function then the code will look like
#include<stdio.h>
#include<stdlib.h>
void euclidean(int a, int b, int * *q, int * *r);
int main(int argc, char ** argv){
int * q;
int * r;
euclidean(5,4, &q, &r);
printf("q = %d, r = %d", *q, *r);
free( q );
free( r );
return 0;
}
void euclidean(int a, int b, int * *q, int * *r){
*q = (int*)malloc(sizeof(int));
*r = (int*)malloc(sizeof(int));
**q = a/b;
**r = a % b;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments