Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pointer of number in C

Assume there’s function that get int * parameter.

void foo(int *x)
{
    
}

If I want to call this function without creating an int variable

int main()
{
    foo(&1);
    return 0;
}

compilation fails and I get this error message:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lvalue required as unary ‘&’ operand

Why 1 has no address? Isn’t that stored in stack ?

>Solution :

Why 1 has no address? Isn’t that stored in stack ?

No – it is just a value.

You need an object to take its address (reference). A constant expression is not such an object.

You can use compound literals to create temporary object:

void foo(int *x)
{
    printf("%d\n", *x);
}

int main(void)
{
    foo( (int[]){1} );
    foo( &(int){1} );
}

https://godbolt.org/z/xvdbTzn3Y

but string constants have addresses what is the difference ?

They are not constant expressions only string literals. String literal is an array of char``[C] or const char``[C++]. String literals cannot be modified (it invokes undefined behabior) . It is an object and you can take the address of it:

void foo(char (*x)[])
{
    printf("'%s'\n", *x);
}

int main(void)
{
    foo(&"dsfgdfsgdfg");
}

https://godbolt.org/z/q9s3P6xcb

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading