首页 > 解决方案 > 如何在C中打印一个向量

问题描述

我有三个不同的向量,里面有不同城镇的名称:

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 中,

如果我放:

printf("%s",listTown1[0] ) 代码显示“Abrera”很好,但我需要像 varName 一样传递向量的名称,因为有时会是 listTown1,有时是 listTown2 或 listTown3 ...

任何想法?谢谢

标签: c

解决方案


你试图做的事情在 C 中不起作用——你不能像那样动态地构建变量名。

每当您发现自己定义了一堆具有相同类型和序号名称( 、 等)的变量时var1var2这就是您想要使用数组的真正强烈暗示。在这种情况下,您可以执行类似的操作

/**
 * 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 中的数组不携带任何有关其大小的元数据,并且在大多数情况下(例如当您将其作为参数传递给函数时)类型的表达式“array of T”将“衰减”为“pointer to”类型的表达式T,因此该sizeof arr / sizeof arr[0]技巧无法获取元素的数量。


推荐阅读