100%的数组在函数中正确,75%的数组在CALLING函数中正确 - C

Ant*_*ara 1 c c++ arrays struct output

注意:我正在使用c ++编译器,因此我可以使用pass by reference

我有一个奇怪的问题,我真的不知道发生了什么.

基本上,我有一个文本文件:http://pastebin.com/mCp6K3HB ,我正在将文本文件的内容读入一个原子数组:

typedef struct{
    char * name;
    char * symbol;
    int atomic_number;
    double atomic_weight;
    int electrons;
    int neutrons;
    int protons;
} atom;
Run Code Online (Sandbox Code Playgroud)

这是我对atom的类型定义.

void set_up_temp(atom (&element_record)[DIM1])
{
    char temp_array[826][20];
    char temp2[128][20];
    int i=0;
    int j=0;
    int ctr=0;

    FILE *f=fopen("atoms.txt","r");

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

    for (j = 0; j < 128; j++)
    {
        element_record[j].name = temp_array[ctr];
        element_record[j].symbol = temp_array[ctr+1];
        element_record[j].atomic_number = atol(temp_array[ctr+2]);
        element_record[j].atomic_weight = atol(temp_array[ctr+3]);
        element_record[j].electrons = atol(temp_array[ctr+4]);
        element_record[j].neutrons = atol(temp_array[ctr+5]);
        element_record[j].protons = atol(temp_array[ctr+6]);
        ctr = ctr + 7;
    }

    //Close the file to free up memory and prevent leaks
    fclose(f);
} //AT THIS POINT THE DATA IS FINE
Run Code Online (Sandbox Code Playgroud)

这是我用来读取数据的函数.当我调试这个函数,并让它运行到最后,我使用调试器检查它的内容,并且数组有100%正确的数据,也就是说,所有元素都是它们应该相对于文本文件. http://i.imgur.com/SEq9w7Q.png此图显示了我在说什么.在左侧,所有元素,0,最多127,是完美的.然后,我将介绍我正在调用它的函数.

atom myAtoms[118];
set_up_temp(myAtoms); //AT THIS POINT DATA IS FINE
region current_button_pressed; // NOW IT'S BROKEN
load_font_named("arial", "cour.ttf", 20); 
panel p1 = load_panel("atomicpanel.txt");   
panel p2 = load_panel("NumberPanel.txt");
Run Code Online (Sandbox Code Playgroud)

一旦调用ANYTHING,在我调用之后set_up_temp,我的阵列的元素103到127变成乱码.随着越来越多的东西被调用,甚至更多的阵列变成了胡言乱语.这很奇怪,我不知道发生了什么......有没有人有任何想法?谢谢.

zwo*_*wol 7

for (j = 0; j < 128; j++)
{
    element_record[j].name = temp_array[ctr];
Run Code Online (Sandbox Code Playgroud)

您正在存储temp_array堆栈中的指针,然后返回指针.你从函数返回的那一刻,所有temp_array无效-这是不确定的行为提领任何点之后的指针."未定义的行为"包括你仍然可以毫无困难地读取元素0到102的可能性,但正如你所说,103到127转向乱码.您需要为这些字符串分配空间,这些字符串与atom对象一样长.因为正如您所说,您使用的是C++,最简单的解决方法是将两个char *成员都更改为std::string.(如果你不想使用std::string,那么第二个最简单的修复是使用strdup,但是你必须free明确地使用那个内存.)

这可能不是此代码中唯一的错误,但它可能是导致您直接问题的错误.

如果你很好奇,对原因的高数据端越来越损坏的是,在大多数(但不是全部)的计算机,包括您所使用的一个,堆栈由高地址向下生长,即低.但是,数组总是从低地址索引到高地址.因此,以前的内存区域的高端temp_array是最接近调用者中的堆栈指针的部分,因此最有可能被后续函数调用覆盖.