可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has an answer here:
typedef struct mobiltelefon { char herstellername[HLEN]; double displaydiagonale; aufloesung_t aufloesung; char standards[NUMBER_OF_STRINGS][STRINGLENGTH+1] = {"GPRS", "EDGE", "HSDPA", "HSUPA", "HSPA", "LTE"}; } telefon_t;
I keep getting an error expected ; at the end of declaration list.
回答1:
Change
char (*standards[6])[5] = {{"GPRS"}, {"EDGE"}, {"HSDPA"}, {"HSUPA"}, {"HSPA"}, {"LTE"}};
to
char standards[6][6] = {{"GPRS"}, {"EDGE"}, {"HSDPA"}, {"HSUPA"}, {"HSPA"}, {"LTE"}};
A quick example:
#include int main(int argc, char *argv[]) { int i; char standards[6][6] = {{"GPRS"}, {"EDGE"}, {"HSDPA"}, {"HSUPA"}, {"HSPA"}, {"LTE"}}; for(i=0;i
Kindly note char standards[6][5] is wrong in your case as the longest string in your 2D array is HSDPA and HSUPA which is of length 5, you will need one more byte for terminating '\0' char.
回答2:
you can use 2D arrays if you know the maximum lenght of the strings you will be putting in it for example if we know that no string will be over 4 characters long then just do
char arr[6][5] = {"GPRS" , "EDGE" , "HSDPA" , ...};
a better way of doing this is
char *arr[] = { "GPRS" , "EDGE" , "HSPDA"}
this way you don't have to worry about the lenght of the strings or how many strings you can add
回答3:
One way to initialize an array of strings is:
char *standards[] = {"GPRS", ...};
You don't have to pass the number of strings, compiler will figure that out.
回答4:
Variables in a structure cannot be initialized.Apparently standards can't be initialized inside the structure.
回答5:
Remove the * and the {}. Change this:
char (*standards[6])[5] = {{"GPRS"}, {"EDGE"}, {"HSDPA"}, {"HSUPA"}, {"HSPA"}, {"LTE"}};
To this:
char standards[6][6] = {"GPRS", "EDGE", "HSDPA", "HSUPA", "HSPA", "LTE"};
To the struct:
You cant initialize a struct member within its declaration. You need to do something like this:
typedef struct mobiltelefon { char herstellername[HLEN]; double displaydiagonale; aufloesung_t aufloesung; char standards[NUMBER_OF_STRINGS][STRINGLENGTH+1]; } telefon_t;
And the initialize the variable like this (C99/C11 only):
telefon_t iphone = {.standards = {"GPRS", "EDGE", "HSDPA", "HSUPA", "HSPA", "LTE"}};
Or with memcpy:
memcpy(iphone.standards[0], "GPRS", 5); memcpy(iphone.standards[1], "EDGE", 5); memcpy(iphone.standards[2], "HSDPA", 6); memcpy(iphone.standards[3], "HSUPA", 6); memcpy(iphone.standards[4], "HSPA", 5); memcpy(iphone.standards[5], "LTE", 4);
But this is a waste of space, if each phone has the same standards I would rather go with a global variable:
char teleon_standards[6][6] = {"GPRS", "EDGE", "HSDPA", "HSUPA", "HSPA", "LTE"};