c - 为什么我的 fprintf 无法将标准输出作为流传递?

标签 c

<分区>

我有以下功能:

void print_out_str(FILE* outstream, UINT x, int n) {

   assert(n >= 1);

   int n1, n2, j;

   n1 = (n - 1)/64; n2 = n % 64;
   for(j = 0; j <= n1 - 1; j++) 
      fprintf(outstream,"%016llx ",x[j]); //padding with 0
   fprintf(outstream,"%016llx ",x[n1] & ((1ULL<<n2) - 1ULL));

“outstream”是我想打印的地方,UINTuint64_t* 的类型定义,n 是一些我要打印的位。

我不明白为什么,但每次我尝试调用此类函数时,程序都会因段错误而崩溃。我已经尝试使用 GDB 来了解变量内容 (outstream, x, n) 是否符合我的预期并且没问题。具体来说,作为一个简单的例子,我尝试了一个包含两个元素的数组,n = 87 和 x[0] = x[1] = 0,outstream = stdout。

我错过了什么吗?

更新:

更多信息...

这是我在提到的函数之前调用的代码:

void test_set_bit() {
   int nbits_to_allocate, i;
   UINT x;

   printf("Set the size of your x var: "); scanf("%d",&nbits_to_allocate);
   init_ui(x,nbits_to_allocate);
   printf("Set the specific bit would you like to set: "); scanf("%d",&i);

   set_ui_zero(x,nbits_to_allocate);
   printf("Content before the bit set:\n");
   print_out_str(stderr,x,nbits_to_allocate);
   //Neglect the following three lines...
   //set_ui_bit(x,nbits_to_allocate,i); 
   //printf("Content after the bit set:\n");
   //print_out_str(stderr,x,nbits_to_allocate);

}

init_ui 在哪里

void init_ui(UINT x, int n) {

   assert(n >= 1);

   int N;
   N = (n + 63)/64;
   x = (UINT)malloc(N*sizeof(uint64_t));
}

最佳答案

在 C 中,函数参数是按值传递 并且在被调用方修改它们不会影响调用方的局部变量。您通过使用具有自动存储持续时间(不确定)的未初始化变量 x 的值调用了未定义的行为

使用指针让调用者修改调用者的局部变量。

void init_ui(UINT *x, int n) { /* add * to declare pointer to UINT */

   assert(n >= 1);

   int N;
   N = (n + 63)/64;
   *x = malloc(N*sizeof(uint64_t)); /* add * to access what is pointed by x */
}

用法:

UINT x;

init_ui(&x,nbits_to_allocate); /* add & to get address of x */

关于c - 为什么我的 fprintf 无法将标准输出作为流传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36008629/

相关文章:

c - 同时标记匹配和转义匹配外的特殊字符

c - c 中的动态类型

c - 如何将 LISP 代码翻译或转换为 C 代码?

c - 将两个文本文件中的两个矩阵相乘,输出为零

C 预处理器 KERNEL_VERSION 引用错误修复

c - libxml2 是 DOM 解析器还是串行解析器?

c - 我应该在我的 C 代码中检测 OOM(内存不足)错误吗?

c - 模拟文件系统访问

c - execvp() 输出为 ncurses 创建缩进

c - C 编程中的 getche