gpt4 book ai didi

c - 更新函数中的字符串数组 - C

转载 作者:太空宇宙 更新时间:2023-11-04 07:01:41 25 4
gpt4 key购买 nike

我正在编写 C 函数,它仅在给定元素唯一时更新字符串数组。我已经像这样实现了这个功能:

char *cities[100];

/* adds 2 names if they're unique instances and updates total number of cities names
if necessary */

int addCity(char* city1, char* city2, char** arr, int amount) {
int toReturn = amount;
int i;
int flag1 = 0;
int flag2 = 0;

// checking whether first city already exists
for (i = 0; i < amount; i++ ) {
if (strcmp(arr[i], city1) == NULL) {
flag1 = 1;
break;
}
}
if (flag1 == 0) {
arr[amount] = city1;
toReturn++;
}
// 2nd city
for (i = 0; i < amount; i++ ) {
if (strcmp(arr[i], city2) == NULL) {
flag2 = 1;
break;
}
}
if (flag2 == 0 && flag1 == 1) {
arr[amount] = city2;
toReturn++;
}
if (flag2 == 0 && flag1 == 0) {
arr[amount+1] = city2;
toReturn++;
}
return toReturn;
}

看起来我在尝试比较 String 数组的元素和 String 本身时收到一些警告(指针和整数之间的比较)。我怎样才能摆脱它?总体而言,此功能还有哪些可以改进的地方?

此外,我怀疑arr[amount] = city1,但是当我使用strcpy()程序时根本不起作用。

最佳答案

看来你需要的是下面的

char *cities[100];

/* adds 2 names if they're unique instances and updates total number of cities names
if necessary */

int addCity( const char *city1, const char *city2, char **arr, int amount )
{
int i;

// checking whether first city already exists
i = 0;
while ( i < amount && strcmp( arr[i], city1 ) != 0 ) i++;

if ( i == amount )
{
arr[amount] = malloc( strlen( city1 ) + 1 );
if ( arr[amount] ) strcpy( arr[amount++], city1 );
}

// 2nd city
i = 0;
while ( i < amount && strcmp( arr[i], city2 ) != 0 ) i++;

if ( i == amount )
{
arr[amount] = malloc( strlen( city2 ) + 1 );
if ( arr[amount] ) strcpy( arr[amount++], city2 );
}

return amount;
}

至于你的代码然后是if语句中的这些条件

if (strcmp(arr[i], city1) == NULL)
if (strcmp(arr[i], city2) == NULL)

错了。应该有

if (strcmp(arr[i], city1) == 0)
if (strcmp(arr[i], city2) == 0)

也在这个代码块之后

if (flag1 == 0) {
arr[amount] = city1;
toReturn++;
}

您还应该增加数量,因为它在下面用作指针数组中的索引。

这两个条件

if (flag2 == 0 && flag1 == 1) {
if (flag2 == 0 && flag1 == 0) {

等同于条件

if (flag2 == 0) {

看来你应该为每个添加的城市动态分配内存。

至于我,那么我会使用函数参数的以下顺序

int addCity( char **arr, int amount, const char *city1, const char *city2 );

或者甚至可以用下面的方式定义函数

int addCity( char **arr, int amount, const char *city )
{
int i;

// checking whether the city already exists
i = 0;
while ( i < amount && strcmp( arr[i], city ) != 0 ) i++;

if ( i == amount )
{
arr[amount] = malloc( strlen( city ) + 1 );
if ( arr[amount] ) strcpy( arr[amount++], city );
}

return amount;
}

并为每个添加的城市分别调用两次。

关于c - 更新函数中的字符串数组 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37308498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com