1

I have the following code written in C:

n.    struct UDSData {
        char *name;
        char *address;
      };

n.    char UDS1[16] = "fill up sixteen", UDS2[16] = "fill up sixteen";

n.    while (something) {
       ...

108.   char UDS1Temp[16], UDS2Temp[16];
109.   strcpy(UDS1Temp, UDS1);
110.   strcpy(UDS2Temp, UDS2);
111.   
112.   struct UDSData item = {UDS1Temp, UDS2Temp};
113.   UDSCodes[UDSTotal++] = item;
     }

Any idea why the code compiles to give these errors:

1><file>(112): error C2143: syntax error : missing ';' before 'type'
1><file>(113): error C2065: 'item' : undeclared identifier
1><file(113): error C2440: '=' : cannot convert from 'int' to 'UDSData'

Removing the strcpy() and inputting UDS1 and UDS2 directly into the struct works.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195
  • Line 112 doesn't make a lot of sense to me but I'm not up to date on C. Which C standard are you using and what type is UDSData? – nvoigt Apr 10 '13 at 08:56
  • Sounds like the compiler does not find this type `UDSData`. Is it defined properly? (`include`d header, no circular dependencies, etc.)? – Kiril Kirov Apr 10 '13 at 08:57
  • @KirilKirov Yes, this type is previously defined. As I had mentioned, it works just fine if I replace UDS1Temp with UDS1, and UDS2Temp with UDS2 in the struct. – Oliver Spryn Apr 10 '13 at 09:00
  • Is the code too long? It will be easier for us to help you if we have the whole code and we can actually try to compile something by ourselves. – Kiril Kirov Apr 10 '13 at 09:03
  • @KirilKirov It's pretty huge and it requires very specialized input in order for it to function... otherwise I would post more. – Oliver Spryn Apr 10 '13 at 09:04
  • Before C99 all variables needed to be declared at the start of a function. `UDS1Temp` and `item` appear to violate this. Which version of C are you trying to compile using? – simonc Apr 10 '13 at 09:04
  • @simonc I tried bringing the declarations to the start, but there was not luck. – Oliver Spryn Apr 10 '13 at 09:06
  • "no luck" as in precisely the same compiler errors? If not, what were the updated errors? – simonc Apr 10 '13 at 09:09
  • That isn't what you say in your question: "Removing the strcpy() ... works." – cdarke Apr 10 '13 at 09:14

1 Answers1

2

You are almost certainly using an early compiler standard, like C89, which does not allow mixed declarations and code. You need to declare item near the start of the code block. Something like this:

char UDS1Temp[16], UDS2Temp[16];
struct UDSData item = {UDS1Temp, UDS2Temp};

strcpy(UDS1Temp, UDS1);
strcpy(UDS2Temp, UDS2);
UDSCodes[UDSTotal++] = item

Since you are only placing the pointers into the struct, the initialisation can be done before the strcpy. But you must declare UDSData after the two char arrays.

cdarke
  • 42,728
  • 8
  • 80
  • 84