Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays C中的Realloc数组和数组排序_Arrays_C_Struct_Realloc - Fatal编程技术网

Arrays C中的Realloc数组和数组排序

Arrays C中的Realloc数组和数组排序,arrays,c,struct,realloc,Arrays,C,Struct,Realloc,我正在研究C,我的情况是: 我有一个struct数组,struct是这样做的 typedef struct text{ int index; //this index is a casual number that i get from the input char *string; char print; }text; 数组具有动态大小。 在text.print(如果必须打印字符串)中,我放置了这个“x”,因此这意味着如果结构包含“x”,我将打印它 在我看来,包含这些结构的数组称

我正在研究C,我的情况是: 我有一个struct数组,struct是这样做的

typedef struct text{
  int index; //this index is a casual number that i get from the input
  char *string;
  char print;
}text;
数组具有动态大小。 在text.print(如果必须打印字符串)中,我放置了这个“x”,因此这意味着如果结构包含“x”,我将打印它

在我看来,包含这些结构的数组称为firstarray,我可以通过一个简单的for来访问它,并且一切都正常

并非firstarray[i]中的所有字符串都必须打印。某些结构在firstarray[i]中没有“x”。请打印

所以我只想在另一个数组中复制带有“x”的结构。 我试着这样做(下面的代码),但我觉得我做错了什么,即使它工作,我浪费了很多空间。 因此,首先我将计算主数组中的所有“x”,并对新数组执行realloc,使其大小等于count。 我将调用新的数组secondarray,结构将是相同的

//count is the number of 'x' that are in the array
secondarray=realloc(secondarray, count*sizeoff(text));
if(secondarray==NULL){
  printf("out of memory\n");
  return 1;
}
j=0;
for(i=0;i<Maxsizefirstarray;i++)
   if(firstarray[i].print=='x'){
      secondarray[j].string=strdup(firstarray[i].string);
      secondarray[j].index=firstarray[i].index;
      secondarray[j].print=firstarray[i].print;
      j++;
};
//count是数组中“x”的数目
secondarray=realloc(secondarray,count*sizeoff(text));
if(secondarray==NULL){
printf(“内存不足\n”);
返回1;
}
j=0;

对于(i=0;i为了避免将整个结构复制到一个新数组中,为什么不每次都在
firstarray
中创建一个索引数组?你能详细说明一下吗?我想我不明白你的建议是什么?如果有帮助的话,我曾经使用嵌套循环以正确的顺序直接从第一个数组打印,但时间复杂度很高太高了。所以我在做另一个数组来降低时间复杂度。我认为@Daniel Farrell的建议是将包含数据的实际
struct
实例与包含数据列表的数组分开。然后在数组中存储一些东西(指针或索引)这样可以找到实际数据。然后您可以创建任意多个数组,但只有一组
struct
s。如果我误解了,很抱歉。效率和可维护性之间有一个折衷,不是吗?您的实现可能没有内存效率,但完全可以理解。您可以节省一点内存在分配内存之前,通过计算需要复制的
struct
实例的数量。如果您有大量数据,则可能需要重新组织以获得更高的效率。@KevinBoone准确地解释了我的想法。我还想补充一点,尝试通过
realloc
释放arr来释放几个字节或几个k如果阵列内存不够满,可能会使您的效率降低,而不是提高效率。除非您能够释放许多兆字节,否则请确保阵列中有足够的内存,并且只增加内存,而不要缩小内存。