Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

initializing an array of structures

Status
Not open for further replies.

xlav

Technical User
Oct 23, 2003
223
JM
Is this how I declare and initialize an array of structures?

typedef struct Sales {
char month[10];
int sales;
}SALES;


SALES[] = { {january, 33}, {february, 67}, {march, 84} };

-X
 
No not really. Are you using c or c++? You need the typedef word if you are using c, not c++.

struct MyStruct
{
char MyData[100];
int MyNum;
}

MyStruct sales[5];

for (int i = 0; i < 5; i++)
{
strcpy(sales.MyData, "Some text");
sales.MyNum = i;
}



Skute

&quot;There are 10 types of people in this World, those that understand binary, and those that don't!&quot;
 
SALES xx[] = { {"january", 33}, {"february", 67}, {"march", 84} };


Ion Filipski
1c.bmp
 
Thanks for both answers, they are both helpful. I'm using C code. Ion has made it easy for me.

-X
 
I want to add two comments:
When initializing as Ion you will get compilation error if the month string has more than 9 characters.
When initializing is done as Skute you should write:
Code:
strcpy(sales[i].MyData, "Some text");
sales[i].MyData[9]='\0';
//or use strcncpy()
strncpy(sales[i].MyData, "Some text",9);
-obislavu-
 
I believe is quite enough for a month to have 10 characters in enclish :)

Ion Filipski
1c.bmp
 
> strcpy(sales.MyData, "Some text");
> sales.MyData[9]='\0';

strcpy() will corrupt any data following sales.MyData, if "Some text" is longer than 10 bytes. If you are not sure, always use strncpy() and add terminating null-character:

strncpy(sales.MyData, "Some text", 9);
sales.MyData[9]='\0';
 
wake up mingis, there is month :), read the original question.

Ion Filipski
1c.bmp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top