我有三个不同的向量,里面有不同城镇的名称:
V_NombrePueblos listTown1={"Abrera","Granollers","Cardedeu","Manresa","Martorell"};
V_NombrePueblos listTown2={"Astorga","Benavente","Bembibre","Camarzana","Ferrol"};
V_NombrePueblos listTown3={"Arteijo","Betanzos","Cariño","Cedeira","Cerdido"};用户告诉我矢量的数量和打印城镇的位置。我认为在使用一个内置开关的函数时,可以这样做:
typedef char nameList[8];
void returnTown(int listTown, int position){
nameList numList;
if (listTown==0){
strcpy(numList, "listTown1");
}
if (listTown==1){
strcpy(numList, "listTown2");
}
if (listTown==2){
strcpy(numList, "listTown3");
}
switch (position){
case 1:
printf("%s", numList[0]);
break;
case 2:
printf("%s", numList[1]);
break;
case 3:
printf("%s", numList[2]);
break;
case 4:
printf("%s", numList[3]);
break;
case 5:
printf("%s", numList[4]);
break;但是当我尝试打印示例时:returnTown(0,1)
控制台没有显示任何内容,使用前面的代码,控制台应该显示"Abrera“
问题就在开关的打印程序上,
如果我说:
printf("%s",listTown1[0] )代码显示"Abrera“很好,但是我需要像varName一样传递向量的名称,因为有时会是listTown1,其他时候是listTown2或listTown3.
有什么想法吗?谢谢
发布于 2020-08-11 14:34:50
复制变量的名称并不意味着引用变量。
要引用变量,应该使用指针。
你会想要这样的东西:
void returnTown(int listTown, int position){
V_NombrePueblos* numList;
switch (listTown){
case 0: numList = &listTown1; break;
case 1: numList = &listTown2; break;
case 2: numList = &listTown3; break;
default: return;
}
if (1 <= position && position <= 5){
printf("%s", (*numList)[position - 1]);(未显示此函数的rest部分,因为我尊重原始代码段)
发布于 2020-08-11 14:47:05
您想要做的事情在C中是行不通的--您不能像这样动态地构建变量名。
每当您发现自己用相同的类型和序号(var1、var2等)定义了一组变量时,这是一个非常强烈的提示,您希望使用数组。在这种情况下,您可以做一些类似的事情
/**
* I am *assuming* that vNombrePueblos is a typedef name for char *[5],
* based on the declarations in your code.
*
* The size of the listTowns array is taken from the number of initializers;
* in this case, 3.
*/
vNombrePueblos listTowns[] = {
{"Abrera","Granollers","Cardedeu","Manresa","Martorell"},
{"Astorga","Benavente","Bembibre","Camarzana","Ferrol"},
{"Arteijo","Betanzos","Cariño","Cedeira","Cerdido"}
};通过这种方式,您不必试图找出您想要的listTownN变量,只需将其索引到这个数组中。要打印出正确的城镇,您所需要的只是两个索引:
/**
* You need to pass the list of towns as an argument to your function;
* since arrays lose their "array-ness" under most circumstances, you also
* have to pass the array size to make sure you don't try to access something
* past the end of it.
*/
void returnTown( vNombrePueblos listTowns[], int numTowns, int town, int position )
{
if ( town < numTowns )
printf( "%s\n", listTowns[town][position] );
else
fprintf( stderr, "No such entry\n" );
}您需要自己跟踪listTowns中的条目数量--C中的数组不携带任何关于它们大小的元数据,而且在大多数情况下(比如将它作为参数传递给函数时),类型“T的数组”的表达式将“衰减”为“指向T的指针”类型的表达式,因此sizeof arr / sizeof arr[0]技巧无法获得元素的数量。
https://stackoverflow.com/questions/63360279
复制相似问题