c - C 中的指针,返回 C 中的额外参数
问题描述
这是我正在处理的问题的简化 C 代码。在实际函数中,我将指针作为参数传递以使其“返回”,因为 foo() 已经返回了某些内容。为什么这会产生分段错误?我如何解决它?
#include <stdio.h>
void foo(int* num_rows){
int row_scan;
printf("enter:\n ");
scanf("%d", &row_scan);
num_rows = &row_scan;
}
int main(void) {
int *num_rows;
foo(num_rows);
printf("%d", *num_rows);
return 0;
}
这是在线代码的链接:https ://repl.it/repls/SilentFreshProperties#main.c
解决方案
在您的代码中,您返回指向在函数返回时停止存在的变量的指针。这是错误的,它被称为未定义的行为
您需要更改逻辑-将资源传递给调用函数中定义的变量(在您的情况下main
)
#include <stdio.h>
void foo(int* num_rows){
int row_scan;
printf("enter:\n ");
scanf("%d", &row_scan);
*num_rows = row_scan;
}
int main(void) {
int num_rows;
foo(&num_rows);
printf("%d", num_rows);
return 0;
}
推荐阅读
- c# - 动态模型绑定客户端
- python - Python Post 请求 - 通过 Outlook API 发送文件时出现 415 错误
- r - 将 data.frame 导出到 xlsx
- c# - 如何防止“索引”在 Action 数组中更新自身
- html - 如何在 XPath/CSS 定位器中排除一个孩子
- c++ - 无法通过 QModelIndex 从 QTreeView 获取项目
- database - 如何从 Visual Studio 2017 将 localdb 发布到 Azure
- azure - Visual Studio 2019 中缺少 Application Insights
- android - React Native 中的序列动画
- c# - 如何找到浏览器当前的显示语言?