C结构数组 [英] Array of C structs

查看:149
本文介绍了C结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个在C结构,并希望将其添加到未设置为一个固定大小的数组,怎么是阵列产生的?

If I create a struct in C and want to add them to an array that is not set to a fixed size, how is the array created?

可以创建这是在获取用户输入并存储该数组中,总是使用相同的tempStruct结构中的循环?在每个迭代上使用的tempStruct

Can one create a tempStruct which is used on every iteration while getting user input and store this in an array, always using the same tempStruct struct in the loop?

数组是如何被创建,如果大小是未知的,因为它依赖于用户的输入,以及如何加入到这个数组结构?

How is an array created if the size is unknown as it depends on user input, and how are structs added to this array?

推荐答案

是的,你可以输入时使用tempStruct您稍后添加到阵列中。

Yes, you can use a tempStruct during input which you add later to the array.

如果数组的大小是未知的,那么你就麻烦了。您必须跟踪该数组的大小的地方。只要有你改变每你改变你的阵列来跟踪你的数组的大小时间整数变量。

If the size of the array is unknown, then you are in trouble. You must keep track of the array's size somewhere. Just have an integer variable that you change every time you change your array to keep track of your array's size.

如果该结构的大小是不是在编译时已知是更加复杂。你要么只存储指针,你必须跟踪阵列中的每个结构的大小这点在内存中实际的结构元素,或数组中为止。在后一种情况下,你会做处理数组中的完全手动计算了不少。虽然这是非常有效的内存,它也容易出错,而且非常难以调试。

If the size of the struct is not known at compile time it is even more complicated. You either just store Pointers in the array which point to your actual struct elements in memory, or you have to keep track of the sizes of every struct in the array. In the later case you would have to do addressing in the array completely manually calculating a lot. While this is very memory efficient, it is also error prone and extremely hard to debug.

确定。样本来创建握住你的使用结构指针数组:

OK. sample to create an array that hold your struct using pointers:

struct MyStruct
{
  /* code */
}

main()
{
  counter = 0;
  struct MyStruct** array = malloc(counter);
  // Create new Element
  struct MyStruct myElement;
  myElement.someData = someValue;

  // Add element to array:
  array = realloc(array, sizeof(struct MyStruct*) * (counter + 1);
  array[counter] = &myElement;
  counter++;

  // Create yet another new Element
  struct MyStruct myElement;
  myElement.someData = someOtherValue;
  array = realloc(array, sizeof(struct MyStruct*) * (counter + 1);
  array[counter] = &myElement;
  counter++;

  // Now remove the last element
  free(array[counter -1]); // may have something more complicated than that, depending on your struct
  array = realloc(array, sizeof(struct MyStruct*) * (counter - 1);
  counter--;
}

这code未测试!

这篇关于C结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆