首页 > 解决方案 > 函数返回零

问题描述

我有数组,其中每个元素的结构都带有名称和整数值。

struct variable_table_element
    {
        char    name[VARIABLE_TABLE_ELEMENT_NAME_SIZE];
        int     value1;
    };

除此之外,我还创建了两个函数。首先填充一个表格元素。其次,通过名称,搜索数组元素并返回它的值。

第一的:

void add_element_to_table(char input_name[VARIABLE_TABLE_ELEMENT_NAME_SIZE], int input_value)
    {
        variable_table[amount_of_full_table_element].value1 = input_value;

        for (int x = 0 ; x < VARIABLE_TABLE_ELEMENT_NAME_SIZE; x++) 
        {
            variable_table[amount_of_full_table_element].name[x] = input_name[x];
        }   


    }

第二:

int return_element_from_table(char input_name[VARIABLE_TABLE_ELEMENT_NAME_SIZE])
    {
        for (int x = 0; x < amount_of_full_table_element; x++)
        {
            if (variable_table[x].name == input_name)
            {
                return variable_table[x].value1;
            }
        }
    }

我在 main() 中执行此操作:

add_element_to_table("name222",4);
int rw = return_element_from_table("name222");

在这种情况下,rw 的值为 0。

标签: carrayschar

解决方案


你的字符串比较有错误。你必须改变

 if (variable_table[x].name == input_name)

到 :-

 if (strcmp(variable_table[x].name, input_name)==0) 

在 C 字符串中,您不能(有用地)使用 比较字符串 ==,您需要使用strcmp().

此外,您忘记增加amount_of_full_table_element的值。所以这个 for 循环for (int x = 0; x < amount_of_full_table_element; x++)总是失败。您需要增加amount_of_full_table_elementin function的值add_element_to_table()

试试这个修改后的代码:-

#include <stdio.h>
#include <string.h>

#define VARIABLE_TABLE_ELEMENT_NAME_SIZE 30
#define MAX_STRING_SIZE 60
#define NUMBER_OF_VARIABLES 30

//structure of element of table
struct variable_table_element
{
    char name[VARIABLE_TABLE_ELEMENT_NAME_SIZE];
    int value1;
};

//global variabels
struct variable_table_element variable_table[NUMBER_OF_VARIABLES];
int amount_of_full_table_element = 0;

// add integer to table
void add_element_to_table(char input_name[VARIABLE_TABLE_ELEMENT_NAME_SIZE], int input_value)
{
    variable_table[amount_of_full_table_element].value1 = input_value;

    for (int x = 0; x < VARIABLE_TABLE_ELEMENT_NAME_SIZE; x++)
        variable_table[amount_of_full_table_element].name[x] = input_name[x];
    amount_of_full_table_element++; // increment amount_of_full_table_elemen
}

int return_element_from_table(char input_name[VARIABLE_TABLE_ELEMENT_NAME_SIZE])
{
    for (int x = 0; x < amount_of_full_table_element; x++)
    {
        if (strcmp(variable_table[x].name, input_name) == 0) // string comparison in c
        {
            return variable_table[x].value1;
        }
    }
    return 0; // default return
}

int main()
{
    add_element_to_table("name222", 4);

    int rw = return_element_from_table("name222");

    printf("%i \n", variable_table[0].value1);
    printf("%i", rw);
    return 0;                                    // main needs a return 0
}

return此外,您忘记为 functionreturn_element_from_table()return 0for提供默认类型main()


推荐阅读