cski
cski

Reputation: 21

constant pointer to structure element in constant structure

I am trying to access structure element via constant pointer. Program works like it should but I got warning 'intialization from incompatible pointer type' and '(near initalization for 'B.settings)'. I don't really know how to correctly initalize it. Can someone pls help me figure that out?

Here's my code :

It's just a snippet of larger part. Idea is to have access to structure variables x,y when moving via pointers to const structure. Hope that make sense.

#include <stdio.h>
#define PGM_STR(X) ((const  char[]) { X })

struct SettingsStruct 
{
    unsigned int x;
    unsigned int y;

}Settings;
  	
struct constitem
{
	const char * const  text;
	const struct constitem *next;
	const struct  SettingsStruct  * settings;
};

struct constitem const  A;

struct constitem const  B = {PGM_STR("x"), &A, &Settings.x };
struct constitem const  A = {PGM_STR("y"), &B, &Settings.y };

static const struct constitem *currMenuPtr=&A; 

void main()
{
	Settings.x = 1;
	Settings.y = 2;

  	printf("%s\n",currMenuPtr->text);
    printf("%d\n",*(currMenuPtr->settings));

    currMenuPtr = currMenuPtr->next;
  	
  	printf("%s\n",currMenuPtr->text);
  	printf("%d\n",*(currMenuPtr->settings));
}

Upvotes: 2

Views: 411

Answers (1)

John Bollinger
John Bollinger

Reputation: 180286

In your code, Settings.x is an unsigned int, and therefore &Settings.x is an unsigned int *. You are trying to use it to initialize a value of type const struct SettingsStruct *. The compiler is quite right to complain -- what you are doing is highly questionable, and I suppose probably not what you actually mean to do. The same applies to Settings.y.

It looks like you could get the compiler to stop complaining (about that) by changing the type of the third element of struct constitem to unsigned int *. You'll have to judge whether that actually works for you in the larger scheme of your program, though.

There is also a problem with using &A in the initializer for variable B when A is not yet declared at the point where the initializer appears. Inasmuch as you also refer to B in A's initializer, you can't solve that by swapping the declaration order. If you really do want a circular chain of pointers, then the pointer values cannot be const, because at least one of them will need to be modified after initialization.

Upvotes: 1

Related Questions