简体   繁体   中英

Assigning a pointer to the const function arguement pointer

Say I have a const pointer to an array as a function argument like so:

int* test(const int* inputArg)

And within the function I want to assign inputArg as one of the members of a struct, like so:

typedef struct {
    int * intArray;
} structSample;

structSample abc;
abc.intArray = inputArg;

How should I cast inputArg to achieve this? Right now if I compile it, error will be shown saying that

error: assigning to 'int *' from 'const int *'

Thank you

First of all, you do not have

a const pointer to an array

What you have is a pointer to constant integer. If you really wanted a constant pointer to integer as an argument, you would have to have the prototype declared as follows:

int* test(int* const inputArg)

Unless, of course, something else was in mind.


Update from comment:

So basically if you want to have a pointer to constant int stored in your function as a struct member, you can declare it just like that:

struct SampleStruct
{
  const int* a;
  /* whatever follows */
};

int* test(const int* inputArg)
{
  struct SampleStruct ss;
  ss.a = inputArg;
  /* other code */
}

You must be aware, that in doing so, you must be const correct. That means, since both (argument and field) are pointers to constant integers, you must not change the values at that address(es).

abc.intArray = (int*)inputArg;

This is the C-style cast . On a side not the compiler didn't allow the const conversion by default because it's dangerous to do so. You are removing the const at your own risk. For eg if your test is called like

const int max = 100;
//centuries later
test(&max);

and you do go ahead with the cast:

abc.intArray = (int*)inputArg;
// after another century later
*(abc.intArray) = 10; // kaboom. Undefined behavior. Debugging is a nightmare at this point

The best solution here would be changing the function to

int* test(int* inputArg)
{
/* do whatever you wish to do with inputArg itself
 * why  bother to create a structure and all?
 * The whole purpose you wanted the const int* inputArg
 * was to prevent any accidental change of data pointed to by it
 * Wasn't it?
 */
}

It looks like that you are using Werror flag (this shouldn't be an error but a warning)

There is a way to lie to the compiler (using unions) without warnings:

#include <stdio.h>

int *test(const int *inputArg)
{
    union {int *nonconstant; const int *constant;} fake = {.constant = inputArg};
    int *p = fake.nonconstant;

    return p;
}

int main(void)
{
    const int x = 500;
    int *p = test(&x);

    *p = 100; /* Boom */
    return 0;
}

As pointed out by others, don't do it :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM