0

So I have a structure, and one of its members is a string.

struct Output {
     char *axis;
     int value;
};
struct Output Jsoutput;

My question is, how do I store a string in axis?

char whichaxis[4][3] = {"LX","LY","RY","RX"};
// Store which  axis and value of the joystick position in Jsoutput
Jsoutput.axis =  whichaxis[jse.number];
printf("%s\n",Jsoutput.axis);

I feel like there should be some & somewhere, but not sure where.

theo-brown
  • 653
  • 10
  • 27
  • What is `whichaxis`'s lifetime? Is it really on the stack like that? Are you planning on writing to the string at `axis`? – Kevin Nov 24 '13 at 18:08
  • It's an event processing thing, so `Jsoutput.axis` will be overwritten regularly with a new pair of characters from `whichaxis`. `whichaxis` will not change, and should stay establsihed. – theo-brown Nov 24 '13 at 18:12
  • So you'll be reassigning `axis`, but never writing, e.g. `Jsoutput.axis[1] = 'x'`? – Kevin Nov 24 '13 at 18:14
  • Oh ok, sorry misunderstood. In my main loop stuff happens if `Jsoutput.axis == "LX"` – theo-brown Nov 24 '13 at 18:19

3 Answers3

4

Just use strdup

Jsoutput.axis =  strdup(whichaxis[jse.number]);
Charlie Burns
  • 6,994
  • 20
  • 29
1

You can copy a String with the function strcpy(destination, source)from string.h

see http://www.cplusplus.com/reference/cstring/strcpy/

Jsoutput.axis =  malloc(3);
strcpy(Jsoutput.axis,whichaxis[jse.number]);
0

You don't have to "store" the string a second time.

char whichaxis[4][3] = {"LX","LY","RY","RX"};

Stores the string.

char *axis;

Says "I'm going to point at a string".

If you wanted a & in there, you could do:

Jsoutput.axis =  & (whichaxis[jse.number][0]) ;

But the original designers of C were very pragmatic and let arrays turn into pointers all the time for convenience. See What is array decaying for more details.

Community
  • 1
  • 1
woolstar
  • 5,063
  • 20
  • 31