首页 > 解决方案 > 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

标签: cpointers

解决方案


在您的代码中,您返回指向在函数返回时停止存在的变量的指针。这是错误的,它被称为未定义的行为

您需要更改逻辑-将资源传递给调用函数中定义的变量(在您的情况下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;  
}

https://godbolt.org/z/xxo4Pr


推荐阅读