0
Write a program in C that reads 2 numbers (integer or real) and prints their sum. The user informs what type of data will be entered. Note: Use only pointers and dynamic memory allocation to solve the problem.
I have this exercise to solve and I ended up doing it this way, the result comes out as expected, however, I do not know if it was done the way it should be done.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main() {
setlocale(LC_ALL, "Portuguese");
int op;
int i1, i2;
float r1,r2;
void *x1, *x2;
printf("M E N U D E I N F O R M A Ç Õ E S\n");
printf("1-Inteiro\n");
printf("2-Float\n");
scanf("%d", &op);
switch(op) {
case 1 :
printf("Digite o primeiro número inteiro: ");
scanf("%d", &i1);
x1 = (int *)malloc((i1 * sizeof(int)));
x1 = &i1;
printf("Digite o segundo número inteiro: ");
scanf("%d", &i2);
x2 = (int *)malloc((i2 * sizeof(int)));
x2 = &i2;
printf("%d", i1 + i2);
break;
case 2 :
printf("Digite o primeiro número real: ");
scanf("%f", &r1);
x1 = (float *)malloc((r1 * sizeof(float)));
x1 = &r1;
printf("Digite o segundo número real: ");
scanf("%f", &r2);
x2 = (float *)malloc((r2 * sizeof(float)));
x2 = &r2;
printf("%.2f", r1 + r2);
break;
}
return 0;
}
It does not have the slightest sense you allocate memory, put the address of the allocated memory on a pointer and then make this pointer point to the address of another variable. I also see no point in allocating a void pointer because you need to know what a pointer is pointing to (a 32-bit or 64-bit int, a float, a double, etc.), study pointer arithmetic.
– anonimo
Try to do without
i1
,i2
,r1
, norr2
and without adding other variables, only with what remains.– pmg