c - 函数返回零
问题描述
我有数组,其中每个元素的结构都带有名称和整数值。
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。
解决方案
你的字符串比较有错误。你必须改变
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_element
in 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 0
for提供默认类型main()
。
推荐阅读
- c++ - C++ 中正确的 typedef 位置
- java - Java程序查找二次方程的整数根
- c# - 在位图上绘制有角度的矩形
- javascript - 使用 ngb-carousel 在单个滑块页面中显示多张图片
- c# - Edge 在重新加载时显示带有“#”符号的空白页
- c# - C# 和 Python 之间的持续通信
- express - 如何防止 mini-css-extract-plugin 创建 js entrypint
- java - Spring - 为每个 bean 使用不同的属性文件
- tree - 如何在 Angular 5 中创建自定义嵌套节点树?我是角度的初学者。我不知道
- python - ValueError:输入 0 与层 lstm_1 不兼容:预期 ndim=3,发现 ndim=2