Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

Passing char ** to a function expecting const char **

As per this question, from c-faq.com, it's not possible to assign a char ** to a const char ** without a cast. The explanation given at the link is perfectly reasonable and easy to understand. Indeed, doing it would violate the promise not to modify the pointed data.

I, cannot understand Why is it illegal to pass it to a funcion?

I can't see why this

void 
function(const char **pointer)
{
    // Prevent modifying pointer
}

int
main(void)
{
    char **pointer;
    // Initialize pointer
    function(pointer);
    return 0;
}

is not possible either.

Upvotes: 0

Views: 646

Answers (1)

interjay
interjay

Reputation: 110069

It isn't allowed for the same reason assigning isn't allowed. To adapt the example from your link:

const char c = 'x';
void function(const char **p2)
{
    *p2 = &c;
}
int main() {
    char *p1;
    function(&p1); //*********
    *p1 = 'X';  
}

If the marked line was allowed, it would allow you to change the value of the constant variable c.

Upvotes: 2

Related Questions