动态更改C

时间:2018-02-21 23:34:28

标签: c

我是C编程新手。如果这个问题不合适,请原谅。我一直在努力动态地改变结构内部变量的大小(而不是结构本身)。让我们说我有一个名为dist1的结构,就像下面的代码一样。我想将此结构传递给函数并动态更改test1的大小。这甚至可能吗?

#include <stdio.h>
struct distance
{
    double *test1;
    double *test2;
};


int main()
{
    struct distance dist1;
    add(&dist1); 

    return 0;
}

void add(struct distance *d3) 
{
     // I want to dynamically change the size of "test1" to let's say test1(50)
     // Is this possible?
}

3 个答案:

答案 0 :(得分:1)

这是不可能的任何有意义的方式。你总是可以让struct distance容器指针加倍而不是双打,然后改变指向内存的大小,但你的目标不明确,所以我不确定它会有什么用处。

答案 1 :(得分:1)

struct distance的成员最好先进行初始化。

struct distance dist1 = { NULL, NULL };

要更改已分配的元素数,请使用realloc()。传递给它d3->test1和所需的字节数。如果返回的值不是NULL,则重新分配成功,代码应该使用它。研究realloc()了解更多详情。

#include <stdlib.h>
void add(struct distance *d3) {
  // I want to dynamically change the size of "test1" to let's say test1(50)
  size_t new_element_count = 50;
  void *tmp = realloc(d3->test1, sizeof *(d3->test1) * new_element_count);
  if (tmp == NULL && new_element_count > 0) {
    Handle_OutOfMemory();
  } else {
    d3->test1 = tmp;
  }
}

答案 2 :(得分:0)

我终于得到了这个运行。我非常感谢大家的帮助和时间。你们真棒!

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

struct distance
{
    double *test1;
    double *test2;
};


void add(struct distance *dist1) ;


int main()
{
    struct distance dist1;

    dist1.test1 = (double *) malloc(5*sizeof(double));
    dist1.test1[4] = 14.22;
    printf("dist1.test1[4] from main() = %f\n", dist1.test1[4]);

    add(&dist1); 

    printf("dist1.test2[3] from main() = %f\n", dist1.test2[3]);

    return 0;
}

void add(struct distance *dist1) 
{
     printf("dist1.test1[4] from add() = %f\n", (*dist1).test1[4]);

     (*dist1).test2 = (double *) malloc(10*sizeof(double));
     (*dist1).test2[3] = 14.67;
     printf("dist1.test2[3] from add() = %f\n", (*dist1).test2[3]);
}
相关问题