arrays - 在 if 语句 C 中声明一个新变量
问题描述
我有一个 Insert
函数,其中有一个char
诸如参数。使用这个参数 ( type
) 我决定了 pos 的类型。例如:如果我打电话 Insert('i')
,我指定我必须使用一个 Int。问题是,如果我在 if 之外的每个 if 语句中声明一个新参数,它就看不到变量。就我而言,printf("%d", array[pos]);
它告诉我pos
没有初始化。我该如何解决?
插入.c
void insert(char type){
if(type=='i'){
int pos;
}else if(type=='f' || type=='d'){
double pos;
}else if(type=='c'){
char pos;
}else if(type=='s'){
char *pos;
}else {
int pos;
}
int array[2];
//I put some values in the array.
printf("%d", array[pos]);
主程序
int main(){
char c = 'i';
insert(c);
解决方案
变量的范围是声明它的块。这意味着pos
变量一到达右括号就会消失。该结构允许您对不同类型使用相同的名称,但 C 不允许您在声明它的块之外使用变量。
您在这里需要的是一个联合,并且为了能够正确使用它,我建议您将它与它的类型指示一起包含到一个结构中:
struct variant {
enum {i, d, c, s} type;
union {
int i;
double d;
char c;
char *s;
};
};
然后你可以使用它:
void insert(char type){
variant pos;
if(type=='i'){
pos.type = i;
}else if(type=='f' || type=='d'){
pos.type = f;
}else if(type=='c'){
pos.type = c;
}else if(type=='s'){
pos.type = s;
}else {
pos.type = i;
}
...
if (pos.type == i) {
printf("%d", array[pos.i]);
推荐阅读
- apache-spark - 如何使用 spark DS 从嵌套的 json 中提取数据?
- css - 如何在多边形的psedo元素周围添加盒子阴影?
- css - 应用了 CSS 类,但没有应用样式
- ruby-on-rails - Turbolinks 访问页面中缺少 hubspot 聊天界面,但可以刷新整个页面
- laravel - 自定义 cron(5 8 * * *) 函数在 laravel 任务调度中不起作用
- github - 如何使用 GitHub 身份验证从 Ubuntu 命令行克隆私有 GitLab 存储库?
- amazon-web-services - CloudWatch 警报到不同区域的 SNS
- angular - 无法将值传递给 Matdialog
- makecert - 使用没有 pvk 文件的 makecert 创建证书
- java - 对错误接口的 Binder 调用