功能改变阵列数据 - 数据未发生变化。 C [英] Function to change array data - data not changing. C

查看:98
本文介绍了功能改变阵列数据 - 数据未发生变化。 C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C,但我在帕斯卡在几个星期前编程。在Pascal中,如果你想改变一个数组中的数据,通过引用传递,通过键入 VAR myArray的本质。我无法弄清楚如何在C.为此,我读过一吨的问题,但似乎没有工作。这里是我到目前为止所。

I'm new to C but I've programmed in pascal a few weeks ago. In pascal, if you want to change an arrays data, you pass by reference, by typing var myArray essentially. I can't figure out how to do this in C. I've read a ton of questions but none seem to work. Here's what I have so far.

void set_up_elements(char (*array_to_populate)[20])
{
    char* buffer;
    FILE *f;
    f=fopen("elementList.txt","r");
    char copied_text[118][20];
    int i=0;
    while (!feof(f))
    {
        fgets(copied_text[i],80,f);
        ++i;
    }
    //Close the file to free up memory and prevent leaks
    fclose(f);
    f = NULL;
}

下面是我code键填充阵列,i的对阵列 copied_text 读周期表中的元素的列表。这部分的工作,它成功地填充数组里面的功能。

Here is my code to populate the array, i read a list of the elements in the periodic table in to the array copied_text. This part works, it successfully populates the array that is INSIDE the function.

int main()
{
    char element_array[118][20];
    set_up_elements(element_array);
<..>
}

这是如何我试图调用它。该数组的内容 element_array 不会改变。有谁知道如何解决这一问题?谢谢你。

This is how i'm trying to call it. The contents of the array element_array doesn't change. Does anyone know how to fix this? Thanks.

推荐答案

在理解问题应用右左的阅读规则...

Apply the right-left reading rule in understanding the problem...

字符element_array [118] [20] 表示element_array是20个字符118块阵列。

char element_array[118][20] means that element_array is an array of 118 blocks of 20 chars.

在另一方面,在字符(* array_to_populate)[20] array_to_populate是一个指针,因为括号包含20个字符数组。

On the other hand, in char (*array_to_populate)[20] array_to_populate is a pointer to an array of 20 chars because of the parens.

您可以使用字符(安培; array_to_populate)。[118] [20] 这意味着array_to_populate是20个字符118块参照

You could use char (&array_to_populate)[118][20] which means that array_to_populate is a reference to 118 blocks of 20 chars.

这表示,最大的问题是,在你的函数,你正在阅读到一个临时数组,你从来没有复制到阵列中的传递。此外,您的文件中读取是错误的大小。以下应把工作做好......

That said, the big issue is that in your function, you are reading into a temporary array that you never copy into the passed in array. In addition, your file read is the wrong size. The following should get the job done...

#define DIM1 118
#define DIM2 20

void set_up_elements(char (&array_to_populate)[DIM1][DIM2])
{
    int i=0;
    FILE *f=fopen("elementList.txt","r");

    for (i = 0; f && !feof(f) && i < DIM1; i++ )
    {
        fgets(array_to_populate[i],sizeof(array_to_populate[0]),f);
    }

    //Close the file to free up memory and prevent leaks
    fclose(f);
}

这篇关于功能改变阵列数据 - 数据未发生变化。 C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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