c - 结构体、指针、通过指针获取字段值

标签 c pointers struct

我的应用程序中有类似于此代码的内容:

#include <stdlib.h>
#include <stdio.h>

typedef struct STH
{
  double *buff;
  int size;
}STH;

void fun1(STH *s)
{
  fun3(s->buff, s->size);
}

void fun3(double *buff, int n)
{
  int i = 0;
  printf("N = %d\n", n);
  for(i=0; i<n; i++)
     printf("%d\n", buff[i]);
}

void fun2()
{
  STH s;

  s.size = 4;
  s.buff = malloc(sizeof(double) * s.size);

  fun1(&s);
}

int main()
{
    fun2();
    return 0;
}

当我尝试打印 fun3 中的缓冲区时,gdb 表示 fun3 中存在错误。当我尝试打印(在 fun2 中)s->size 的值时,出现错误(而不是 4,它打印出奇怪的数字...... )

最佳答案

buff[i] 是一个 float ,使用 %f 格式说明符来打印它。 IE。使用:

printf("%f\n", buff[i]);

而不是

printf("%d\n", buff[i]);

此外,您还没有将数组初始化为某些值。它将包含(并打印)随机值。

关于c - 结构体、指针、通过指针获取字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20937595/

相关文章:

c - 带有用户输入的结构数组内的 strstr char 数组

c - C++ 中的 EOF 函数 |c

c++ - 意外的大 u16_t buf

c# - 将结构与 WCF 服务一起使用

c - 我对 C 中按值复制/按引用复制的理解是否正确?

c - intt *p=a 和 int *p1=&a 之间的区别

c++ - 什么时候为struct预留内存空间?

C 程序 我想知道是否有办法简化我的 dayofyear 程序?

c - 释放结构中的数组

c - 如何跳出嵌套循环?