How do I define and initialize an array of strings inside of a struct? [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

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"}; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!