Reputation: 805
Easy question...I know a lot of the values ahead of time, and need to add others later, but why doesn't this compile on the line "direc[i] = {L"Jim",L"Smith"};" where I know the values?
struct NARRAY
{
TCHAR *sFName;
TCHAR *sLName;
};
void main()
{
struct NARRAY direc[1000];
DWORD i = 0;
direc[i].sFName = calloc(512,sizeof(TCHAR));
direc[i].sLName = calloc(512,sizeof(TCHAR));
direc[i] = {L"Jim",L"Smith"};
}
Upvotes: 0
Views: 735
Reputation: 409176
You are trying to use structure/array initialization, which is only allowed when declaring variables. You have to initialize each member by itself:
direct[i].sFname = L"Jim";
direct[i].sLname = L"Smith";
Of course, if you dynamically allocate these members for some entries in the array, and statically (like in my example above) for some entries, you really have no way of knowing which was allocated dynamically or not, which will lead to problems when you come to free those pointers. You can use strdup
(or rather, _tcsdup
for TCHAR
) then:
direct[i].sFname = _tcsdup(L"Jim");
direct[i].sLname = _tcsdup(L"Smith");
Upvotes: 1
Reputation: 571
You need to use a function such as memcpy
or strncpy
to copy your data to the allocated memory.
memcpy(direc[i].sFName, "Jim", 3);
direct[i].sFName[3] = '\0';
Upvotes: 0
Reputation: 399843
Classical C doesn't have struct literals. You can only use that syntax when initializing a variable, i.e. as partof its definition.
However, C99 introduced compound literals, which would allow you to write it like so:
direc[i] = ((struct NARRAY) { L"Jim", L"Smith" });
Upvotes: 1