I'm trying to allocate memory through a function and store the proper data type in that memory, but my int didn't work without (*int), how do I apply that as a double? (*double) is not working
#include <stdio.h>
#include <stdlib.h>
int newInt ();
double newDouble ();
int main() {
int userChoice;
int userValue;
int *intPtr;
double *doublePtr;
printf("Please choose which type of value you'd like to store (1-4).");
puts("\n 1.) Int \n 2.) Double \n");
scanf("%d", &userChoice);
if (userChoice == 1) {
intPtr = (int*)newInt();
printf("You chose an Int, please enter an Int value\n");
scanf("%d", *&intPtr);
printf("Memory value is %p \n", intPtr);
printf("Stored value is %d", *intPtr);
} else if (userChoice == 2) {
doublePtr = (double*)newDouble();
printf("You chose a Double, please enter a Double value\n");
scanf("%lf", *&doublePtr);
printf("Memory value is %p \n", doublePtr);
printf("Stored value is %lf", *doublePtr);
return 0;
}
int newInt () {
malloc(sizeof(int));
}
double newDouble () {
malloc(sizeof(double));
}
I fixed it.
Corrections in the comments.
IDEOne Link
#include <stdio.h>
#include <stdlib.h>
int* newInt (); // Changed the return type
double* newDouble (); // Changed the return type
int main() {
int userChoice;
// int userValue; Removing unused variable.
int *intPtr;
double *doublePtr;
printf("Please choose which type of value you'd like to store (1-4).");
puts("\n 1.) Int \n 2.) Double \n");
scanf("%d", &userChoice);
if (userChoice == 1) {
intPtr = newInt(); // Removed cast
printf("You chose an Int, please enter an Int value\n");
scanf("%d", intPtr); // Removed extra *&
printf("Memory value is %p \n", intPtr);
printf("Stored value is %d", *intPtr);
} else if (userChoice == 2) {
doublePtr = newDouble(); // Removed cast
printf("You chose a Double, please enter a Double value\n");
scanf("%lf", doublePtr); // Removed extra *&
printf("Memory value is %p \n", doublePtr);
printf("Stored value is %lf", *doublePtr);
}
return 0;
} // Added a missing bracket.
int* newInt () { // Changed the return type
return malloc(sizeof(int)); // Added a return statement
}
double* newDouble () { // Changed the return type
return malloc(sizeof(double)); // Added a return statement
}
Related
I have this weird problem. When I write a double type number, it gets stored in the
double data;
variable. Then when I compile and run the code the number gets printed out as for example 3697.0000 when I have written 3697.47595.
Here is the code:
#include <stdio.h>
const int n = 12;
int stack[n], top = -1;
double Read()
{
int x = 0;
if(top < 0)
printf("Empty stack!");
else
{
x = stack[top];
top--;
}
return x;
}
void Write(int x)
{
if(top == n-1)
printf("The stack is full");
else
{
top++;
stack[top] = x;
}
}
int main()
{
double data;
printf("Enter a double (0 for quit): ");
scanf("%lf", &data);
while(data > 0)
{
Write(data);
printf("Enter a double (0 for quit): ");
scanf("%lf", &data);
}
printf("---------------------------");
printf("\nThe stack contains:\n");
while(top >= 0 )
printf("%lf ", Read());
return 0;
}
The value is truncated to int because the elements of the array stack, the argument of Write, and the variable x to temporarily store the value in Read are int. Use double for them to deal with double value.
Given two numbers, n and q, I want to find two numbers, m and p, such that n=m*p and q= m+p. I compiled the code but it returned the error message every time even if the entered values are valid. Is something wrong with the loop?
edit**
input n: 100
input q: 25
still returns the error message even if m=20, p=5 works
#include <stdio.h>
int main(void){
int *mAddress = NULL;
int *pAddress = NULL;
int n;
printf("enter integer: ");
scanf("%d", &n);
int q;
printf("enter query number: ");
scanf("%d", &q);
int m;
int p;
for (m=1; m<=n; m++){
if(n%m == 0){
p = n/m;
if (m+p == q){
mAddress = &m;
pAddress = &p;
printf("The values are %d %d", m, p);
break;
}
else{
printf("could not find any numbers");
break;
}
}
}
You should not break the loop in the case you don't find it for the first time. Instead you should continue this to happen for each n%m == 0 case.
Eventually when you know that nothing hasn't been found print the error message.
I've added a bool to hold if you have found a pair or not and use it to print the error message.
#include <stdio.h>
#include <stdbool.h>
int main(void){
int *mAddress = NULL;
int *pAddress = NULL;
int n;
printf("enter integer: ");
scanf("%d", &n);
int q;
printf("enter query number: ");
scanf("%d", &q);
int m;
int p;
bool found = false;
for (m=1; m<=n; m++){
if(n%m == 0){
p = n/m;
if (m+p == q){
mAddress = &m;
pAddress = &p;
printf("The values are %d %d", m, p);
found = true;
break;
}
}
}
if (!found) {
printf("could not find any numbers");
}
}
Try it out yourself
You miss for loop bracket after if.
for (m=1; m<=n; m++){
if(n%m == 0){
p = n/m;
if (m+p == q){
mAddress = &m;
pAddress = &p;
printf("The values are %d %d", m, p);
break;
}}
I have begin learning pointers in C.
When I try to return pointer in a function, I'm getting segmentation fault error.
Here is the code :
#include<stdio.h>
int *sum(int *, int *);
int main(void)
{
int a, b;
int *ans = NULL;
printf("Enter number a : ");
scanf("%d", &a);
printf("Enter number b : ");
scanf("%d", &b);
ans = sum(&a, &b);
printf("Sum = %d", *ans);
return 0;
}
int *sum(int *p, int *q)
{
int *result = NULL;
*result = *p + *q;
return (result);
}
And the output :
Enter number a : 10
Enter number b : 20
Segmentation fault
Segmentation fault occurs in sum function, when result is declared as pointer. However, I am unable to figure out the reason for the same. Any help regarding this is really appreciable.
You are initing a pointer to NULL and then you are deferencing it: it is Undefined behavior
Change sum function to
int *sum(int *p, int *q)
{
int *result = malloc(sizeof(int));
// check if malloc returned a valid pointer before to dereference it
if (result != NULL)
{
*result = *p + *q;
}
return (result);
}
and add a free call to free the allocated memory.
// check if sum function allocate the pointer before to dereference it
if (ans != NULL)
{
printf("Sum = %d", *ans);
}
free(ans);
return 0;
}
You could also avoid to use pointer to return value:
#include<stdio.h>
int sum(int *, int *);
int main(void)
{
int a, b;
int ans;
printf("Enter number a : ");
scanf("%d", &a);
printf("Enter number b : ");
scanf("%d", &b);
ans = sum(&a, &b);
printf("Sum = %d\n", ans);
return 0;
}
int sum(int *p, int *q)
{
int result = *p + *q;
return (result);
}
The sum function could also be like:
int sum (int *p, int *q)
{
return (*p + *q);
}
EDIT
As #JonathanLeffler wrote in his answer you can do also:
#include<stdio.h>
void sum(int *, int *, int *);
int main(void)
{
int a, b;
int ans;
printf("Enter number a : ");
scanf("%d", &a);
printf("Enter number b : ");
scanf("%d", &b);
sum(&ans, &a, &b);
printf("Sum = %d\n", ans);
return 0;
}
void sum(int *result, int *p, int *q)
{
*result = *p + *q;
}
Allocate memory before trying to store anything, and check the return of malloc()
int *result = NULL;
result = malloc(sizeof(*result));
if(result != NULL)
*result = *p + *q;
else
printf("malloc returned error");
Also, check the return of the function in main() and exit accordingly.
int main(void)
{
.
.
.
ans = sum(&a, &b);
if(ans == NULL)
return 0;
printf("Sum = %d\n", ans);
free(ans); //free the memory then
return 0;
}
A third alternative is to declare ans as a normal int variable in the main function and pass a pointer to it to the sum function, like you do with the other two arguments. This is actually emulating call by reference.
#include<stdio.h>
int *sum(int *, int *);
int main(void)
{
int a, b;
printf("Enter number a : ");
scanf("%d", &a);
printf("Enter number b : ");
scanf("%d", &b);
int* ans = sum(&a, &b);
printf("Sum = %d", *ans);
return 0;
}
int *sum(int *p, int *q)
{
int plus = *p + *q;
int *ans = +
return ans;
}
Store the Sum in a Different variable plus and create a pointer *ans that points to that variable plus and return the pointer variable ans that holds the address of plus
I have been asked to make a code that will rearrange 3 entered integers into ascending/descending order using pointers.
I need to use the function order() to return a pointer to either function ascending3() or descending(), depending on what value of 'e' is entered.
I keep getting an error on the line specified in the readInts() function and am not sure how to fix it.
ERRORS
lvalue required as unary ‘&’ operand" -- The error for `ptr = &(order(e))`
warning: assignment makes pointer from integer without a cast -- The error for `ptr=order(e)`
Pointer code
void readInts(){
int *a,*b,*c;
char e;
int (*ptr1)(int*,int*,int*);
int result;
printf("Enter Integer 1:");
scanf("%d", a);
printf("Enter Integer 2:");
scanf("%d", b);
printf("Enter Integer 3:");
scanf("%d", c);
printf("Enter either A or D:");
scanf(" %c", &e);
ptr1 = &(order(e)); /*ERROR HERE*/
result = (*ptr1)(a,b,c);
printf("%d %d %d", a, b, c);
}
Functions
int ascending3(int* x, int* y, int* z)
{
/*removed sorting code for the sake of shortening the question*/
*x=smallest;
*y=middle;
*z=largest;
}
int descending(int* x, int* y, int* z)
{
int swap;
ascending3(x,y,z);
swap=*x;
*x=*z;
*z=swap;
}
int (*order(char e))(int*x ,int*y,int*z)
{
if(e=='a')
{
return ascending3;
}
else if(e =='d')
{
return descending;
}
return;
}
A function cannot return a function. For this reason you cannot apply the address of operator (&) to the result of your function (to retrieve an address). But a function can return a pointer to a function.
The name of a function in C (prefixed or not by the & operator) is always set as the address of the function, that's a pointer to that function.
The correct code is:
int ascending3(int *x, int *y, int *z);
int descending(int *x, int *y, int *z);
typedef int (*fn)(int *x, int *y, int *z);
fn order(char e)
{
if (e == 'a')
{
return ascending3;
}
else if (e == 'd')
{
return descending;
}
return NULL;
}
void readInts(void)
{
int *a, *b, *c;
char e;
fn ptr1;
int result;
printf("Enter Integer 1:");
scanf("%d", a);
printf("Enter Integer 2:");
scanf("%d", b);
printf("Enter Integer 3:");
scanf("%d", c);
printf("Enter either A or D:");
scanf(" %c", &e);
ptr1 = order(e);
result = (*ptr1) (a, b, c);
printf("%p %p %p", a, b, c);
}
Where I used a typedef to declare the type of our function pointer (and also 2 prototypes for the ordering functions).
If you like to have the asterisk to better show the pointer nature of our type, you can define fn as function (not a pointer to function):
typedef int (fn)(int *x, int *y, int *z);
So you can use the asterisk notation:
typedef int fn(int *x, int *y, int *z);
fn *order(char e)
{
if (e == 'a')
{
return ascending3;
}
else if (e == 'd')
{
return descending;
}
return NULL;
}
void readInts(void)
{
int *a, *b, *c;
char e;
fn *ptr1;
int result;
printf("Enter Integer 1:");
scanf("%d", a);
printf("Enter Integer 2:");
scanf("%d", b);
printf("Enter Integer 3:");
scanf("%d", c);
printf("Enter either A or D:");
scanf(" %c", &e);
ptr1 = order(e);
result = (*ptr1) (a, b, c);
printf("%p %p %p", a, b, c);
}
I was trying to co
So, I don't understand the reason why my compiler is not letting me take input when the convhex() is called from the main. It's directly printing some result.. I don't understand this.
Here's the code..
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <String.h>
void convhex();
void convert(int no, int base);
int checkValid(int base,int no);
// function prototyping done here
void convhex()
{
char ch[10];
int dec=0;
int i, res;
printf("Enter the hexadecimal number \n");
scanf("%[^\n]", ch);
// print in decimal
for(i=strlen(ch)-1;i>=0;i--)
{
if(ch[i]>65)
res=ch[i]-65+10;
else
res=ch[i]-48;
//printf("%d", res);
dec=dec+pow(16,strlen(ch)-(i+1))*res;
}
printf("\nThe number in decimal is %d \n", dec);
}
int checkValid(int base,int no)
{
int rem;
//flag;
// flag=0;
while(no>0)
{
rem=no%10;
if(rem>base)
{
//flag=1;
//break;
return 0;
}
no/=10;
}
return 1;
/*
if(flag==1)
printf("Invalid Input");
else
printf("Valid Input");
*/
}
void convert(int no, int base)
{
int temp, mod, sum=0, i=0;
temp=no;
while(temp>0)
{
mod=temp%10;
temp=temp/10;
sum=sum+pow(base,i)*mod;
i++;
}
printf("\n The number in base 10 is %d", sum);
}
int main()
{
int base, no;
printf("Enter the base \n");
scanf("%d", &base);
if(base==16)
convhex();
else
{
printf("Enter the number \n");
scanf("%d", &no);
printf("You have entered %d", no);
if(checkValid(base, no))
convert(no, base);
}
return 0;
}
// up until now our program can work with any base from 0-10 but not hexadecimal
// in case of hex, we have A-F
scanf in convhex is reading the \n left by the scanf in main.
Try this
scanf(" %[^\n]", ch);
^ An extra space will eat any number of white-spaces.
you can just remove the %[^\n] from scanf in connhex to change it to:
scanf("%s", ch)
or you could do what haccks suggested in the above post.