我想返回人口数量最小的城市的名称(如果它是第二个城市)。 (请不要介意 if 语句,我知道它很乏味),缺少返回值让我烦恼。
我认为我应该在函数 rSmallestCity
中声明一个指针,如 *rtrn
但我猜源变量在使用之前就被销毁了?
typedef struct Coordinate{
int x,y;
}Coordinate;
typedef struct city{
char name[20];
int population;
Coordinate coordinates;
}city;
char *rSmallestCity(city **cl, int n)
{
char *rtrn = NULL;
if(cl[n-2]->population>cl[n-1]->population)
{
rtrn = &cl[n-1]->name;
}
return rtrn;
}
int main()
{
city c1 ={.name="Mumbai", .population=310, .coordinates.x=3, .coordinates.y=4};
city c2 ={.name="Delhi", .population=300, .coordinates.x=3, .coordinates.y=2};
city *clist[2];
clist[0]=&c1;
clist[1]=&c2;
printf("\n%s is smallest\n",rSmallestCity(clist,2));
}
warning: assignment to 'char ' from incompatible pointer type 'char ()[20]' [-Wincompatible-pointer-types]|
最佳答案
我假设我应该在函数 rSmallestCity 中声明一个指针,例如 *rtrn 但我猜源变量在使用之前就被销毁了?
问得好。你的假设是正确的。在函数内部创建变量,它的存在在离开函数时结束。但在本例中,由于结构成员 name
已经是 char *
,因此您不需要创建另一个变量。只需返回c1.name
。 (请参阅下面的代码示例。)
其他一些建议:
在结构声明中:
typedef struct Coordinate{
int x,y;
}Coordinate;
您对结构名称及其 typedef 使用了相同的符号(坐标
)。这不是一个好的做法。如果您同时需要结构名称和 typedef,请选择不同的符号。顺便说一句,在这个例子中,只需要其中之一。假设您选择 typedef,则该结构完全由以下方式定义:
typedef struct {
int x,y;
}Coordinate;
该建议适用于示例代码中的两个 struct
声明。
main
函数的签名不包含 int main(){...}
而
int main(void){..., return 0;}
和 int main(int argc, char *argv[]){..., return 0;}
以下代码示例说明了有关改进帖子下评论的一些其他建议,
typedef struct {
int x,y;
}Coordinate;
typedef struct {
char name[20];
int population;
Coordinate coordinates;
}city;
//return char * rather than char to allow for full null terminated char array (string)
char * rSmallestCity(city c1[],int cityCount)//generisize function prototype to
{ //to easily accommodate bigger arrays if needed
long long size, sizeKeep = 8e9; //index and population. initialize larger than possible population
int indexKeep = 0;
//note you do not need to define a char *, the struct already contains one
for(int i=0; i<cityCount; i++)//use a loop rather than a single comparison, keep the smalles
{
size = c1[i].population;
sizeKeep = (size < sizeKeep) ? indexKeep = i, size : sizeKeep;
}
printf("\n%s\n",c1[indexKeep].name);
return c1[indexKeep].name;
};
int main(void)//use minimum signature for main, and call return before leaving.
{
//combining your original declarations and assignments for struct
//into a single declaration/definition.
city c1[] = {{.name="Mumbai", .population=310, .coordinates.x=3, .coordinates.y=4},
{.name="Delhi", .population=300, .coordinates.x=3, .coordinates.y=2}};
int cityCount = sizeof(c1)/sizeof(c1[0]);
printf("\n%s is smallest",rSmallestCity(c1, cityCount));
return 0;
};
关于c - 将结构体中的字符串传递给函数并返回它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60929646/