trouble accessing external float array

陌路散爱 提交于 2019-12-11 05:14:43

问题


I have the following program in two files

main.cpp

    float POW10[300];
    main(0
    {
        Fill_POW10();
    }

Fill.cpp

extern float *POW10;
Fill_POW10()
{
  for(int i=0;i<300;i++)
  {
    POW10[i]=i;
  }
}

This crashed with a segmentation fault. When I inspect, POW10 is NULL. However if I change Fill.cpp to

extern float POW10[];
Fill_POW10()
{
  for(int i=0;i<300;i++)
  {
    POW10[i]=i;
  }
}

the code works fine. I was thinking that POW10 is actually implemented as a pointer to floats and so the codes should be identical. Can you please explain why this is not so.


回答1:


First read this entry which explains your issue:

http://c-faq.com/aryptr/aryptr1.html

Then read this follow up which explains the differences between array and pointer.

http://c-faq.com/aryptr/aryptr2.html




回答2:


Arrays and pointers are completely different types. When you define a pointer variable, all you get is a single pointer that may or may not actually point anywhere. When you define an array, you get a contiguous sequence of objects.

You may be thinking of function argument types, where array types are transformed to pointer types. That is, void foo(int arg[]) is equivalent to void foo(int* arg). This is only true for function arguments.




回答3:


The type of POW10 is array of 300 float. It is not pointer to float. When you change your extern declaration to match the definition the problem goes away.




回答4:


Because the linker is not resolving your float * POW10 declaration to the float POW10[] definition, but actually creating a separate definition altogether, which ends up being uninitialized (NULL, as you experienced).



来源:https://stackoverflow.com/questions/16323228/trouble-accessing-external-float-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!