本文介绍了按编号引用结构成员。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 问候 对于某些操作,我希望能够轻松访问struct 成员。这是一个例子。 struct mystruct { char member1 [3]; char member1 [50]; char member1 [12]; }; / *打印结构中的字符串* / for(i = 0; i< 3; i ++){ switch(i): case 0: printf("%s\r\ n",mystruct.member1); 休息; 案例0: printf (%s\r\ n,mystruct.member2); 休息; 案例0: printf(" ;%s \\ n",mystruct.member3); 休息; } 这是非常cumbersom,特别是大型结构。是否有某种方式 我可以避免为每个成员命名? 类似下面的伪代码; for(i = 0; i< 3; i ++){ 打印会员我 } 我很感激这方面的建议。 问候。 解决方案 一个ptr到char的数组? char * jagged_array [3]; jagged_array [0] = malloc(3); if(!jagged_array [0]) abort(); jagged_array [1] = malloc(50); if(!jagged_array [1]) abort(); jagged_array [2] = malloc(12); if(!jagged_array [2]) abort(); 显然这可以变成一个函数 打印: - for(i = 0; i< 3; i ++) printf("%s" jagged_array [i]); 代码未编译 - Nick Keighley 一个ptr到char的数组? 3动态分配,3次失败测试和3次malloc开销:-( 我真的更喜欢 struct mystruct { char member1 [3]; char member1 [50]; char member1 [12]; char * memtab [3]; }; void init_mystruct(struct mystruct * s){ s - > memtab [0] =&(s-> member1); s-> memtab [1] =&(s-> member2); s-> memtab [2] =&(s-> member3); } Marc Boyer GreetingsFor certain operations I would like to have easy access to structmembers. Here is an example.struct mystruct {char member1[3];char member1[50];char member1[12];};/* print the strings in the struct */for(i=0; i<3; i++){switch(i):case 0:printf(" %s\r\n", mystruct.member1 );break;case 0:printf(" %s\r\n", mystruct.member2 );break;case 0:printf(" %s\r\n", mystruct.member3 );break;}This is very cumbersom, sepecially for large structs. Is there some wayI could avoid having to name each member?something like the following pseudocode;for(i=0; i<3; i++){print member i}I would appreciate advice on this.Regards. 解决方案an array of ptr to char?char* jagged_array [3];jagged_array[0] = malloc(3);if (!jagged_array[0])abort();jagged_array[1] = malloc(50);if (!jagged_array[1])abort() ;jagged_array[2] = malloc(12);if (!jagged_array[2])abort();obviously this can be turned into a functionprinting:-for (i = 0; i < 3; i++)printf ("%s" jagged_array[i]);code not compiled--Nick Keighleyan array of ptr to char?3 dynamic allocations, 3 failure tests and 3 malloc overhead :-(I would really preferstruct mystruct {char member1[3];char member1[50];char member1[12];char* memtab[3];};void init_mystruct( struct mystruct* s){s->memtab[0]= &(s->member1);s->memtab[1]= &(s->member2);s->memtab[2]= &(s->member3);}Marc Boyer 这篇关于按编号引用结构成员。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-05 08:05