Reputation: 673
why cannot I use struct like this?
typedef struct { unsigned char FirstName; unsigned char LastName; unsigned int age; } User;
User UserNick = {Nick, Watson, 24};
NSLog(@"Your paint job is (R: %NSString, G: %NSString, B: %u)",
UserNick.FirstName, UserNick.LastName, UserNick.age);
I mean I have used a struct like this for sure:
typedef struct {unsigned char red; unsigned char green; unsigned char blue; } Color;
Color carColor = {255, 65,0};
NSLog(@"Your paint job is (R: %hhu, G: %hhu, B: %hhu)",
carColor.red, carColor.green, carColor.blue);
Upvotes: 1
Views: 92
Reputation: 2826
In your definition, FirstName
is an unsigned char which means it is a variable that can hold only one char
as its value. However, Nick
is a string, namely an array of chars.
One could do
typedef struct {
unsigned char * FirstName;
unsigned char * LastName;
unsigned int age;
} User;
User Nick = {"Nick", "Watson", 24};
Upvotes: 1
Reputation: 318934
If you want to use C strings you need the following code:
typedef struct { unsigned char *FirstName; unsigned char *LastName; unsigned int age; } User;
User UserNick = {"Nick", "Watson", 24};
NSLog(@"Your paint job is (R: %s, G: %s, B: %u)",
UserNick.FirstName, UserNick.LastName, UserNick.age);
C strings are char *
. C string literals need to be in quotes. %s
is the format specifier for C strings.
One other suggestion - start field names (and variables names) with lowercase letters.
And since you are working with Objective-C, you would probably end up being better off if you make User
a real class instead of a struct
. Then you can use properties and proper memory management. The names could be NSString
instead of C strings. This makes it easy to store the objects in collections and do other useful things that are hard with a plain old struct
.
Upvotes: 7