我正在使用两个不同的数组。对于其中一个,我得到了我想要的确切结果,而另一个则没有那么多。我通过读取类似于以下内容的文本文件来归档数组:
2597
283
4
723
21
82
426
前五行是客户 ID。总是有 5 行,但它们并不总是有值。下一行是供应商数量,然后是供应商 ID。
void use_arrays()
{
int
i,
customer_count,
*customer_ids,
vendor_count,
*vendor_ids;
customer_ids = malloc(sizeof(int));
vendor_ids = malloc(sizeof(int));
fill_arrays(&customer_count, customer_ids, &vendor_count, vendor_ids);
for (i = 0; i < customer_count; i++)
{
printf("Customer[%d]: %d\n", i, customer_ids[i]);
}
for (i = 0; i < vendor_count; i++)
{
printf("Vendor[%d]: %d\n", i, vendor_ids[i]);
}
free(customer_ids);
free(vendor_ids);
}
void fill_arrays(int *customer_count, int *customer_ids, int *vendor_count, int *vendor_ids)
{
int
i,
*temp,
customer_id,
vendor_id,
num_cust = 0;
FILE
*inp_file;
char
*endptr = NULL,
buffer[500];
inp_file = fopen(g_filename, "r");
for (i = 0; i < 5; i++) /* Can't be more than 5 customers */
{
fgets(buffer, sizeof(buffer), inp_file);
customer_id = strtol(buffer, &endptr, 0);
if (customer_id != 0)
{
customer_ids[i] = customer_id;
temp = realloc(customer_ids, (i+2)*sizeof(int));
if (temp != NULL)
{
customer_ids = temp;
}
else
{
printf("Couldn't allocate memory\n");
}
num_cust++;
}
}
*customer_count = num_cust;
/* Next is number of vendor ids*/
fgets(buffer, sizeof(buffer), inp_file);
*vendor_count = strtol(buffer, &endptr, 0);
temp = realloc(vendor_ids, *vendor_count*sizeof(int));
if (temp != NULL)
{
vendor_ids = temp;
}
else
{
printf("Couldn't allocate memory\n");
}
for (i = 0; i < *vendor_count; i++)
{
fgets(buffer, sizeof(buffer), inp_file);
vendor_id = strtol(buffer, &endptr, 0);
if (vendor_id != 0)
{
vendor_ids[i] = vendor_id;
}
}
fclose(inp_file);
}
数组打印出来后,customer_ids
显示正确的数字,但 vendor_ids
正在从内存中打印随机数。更令人沮丧的是,它从 fill_arrays
内部正确打印了供应商。
最佳答案
如果您想像在 fill_arrays
中那样修改 vendor_ids
,那么您必须将其作为指向指针的指针传递:
fill_arrays(int *customer_count, int *customer_ids, int *vendor_count, int **vendor_ids)
这样调用它:
fill_arrays(&customer_count, customer_ids, &vendor_count, &vendor_ids);
然后你可以像这样重新分配:
temp = realloc(*vendor_ids, *vendor_count*sizeof(int));
if (temp != NULL)
{
*vendor_ids = temp;
}
此外,在函数结束时:
vendor_ids[i] = vendor_id;
必须更改为
(*vendor_ids)[i] = vendor_id;
您还必须对 customer_ids
进行相同的更改。 customer_ids
正常工作而 vendor_ids
不正常的事实可能是由于您使用了 realloc
。如果 realloc 决定必须将内存块重新分配到新位置,您将遇到这些问题,但如果在同一位置重新分配内存,则传入的指针仍然指向那里。由于您永远不知道 realloc
是否会做出该决定,因此 customer_ids
和 vendor_ids
都应作为指向指针的指针传入。
关于c - 如何从c中的动态数组中访问数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14466281/