[英]Printing a populated array of strings prints garbage
I'm just getting into C with a previous knowledge of RPG coding. 我只是以RPG编码的先前知识开始使用C。 Like many before me, I'm confused about strings, arrays and pointers and how to work with them.
像我之前的许多人一样,我对字符串,数组和指针以及如何使用它们感到困惑。
I'm working on a program which takes the name, equatorial radius and polar radius of the planets from a data file, and then calculates and outputs volume, surface area. 我正在开发一个程序,该程序从数据文件获取行星的名称,赤道半径和极地半径,然后计算并输出体积,表面积。
My main function has the following declarations: 我的主要功能有以下声明:
double equi_rad[iNumPlanets]; /* equitoral radii of planets */
double pol_rad[iNumPlanets]; /* polar radii of planets */
char *name[iNumPlanets]; /* array containing planet name */
( iNumPlanets
has already been initialized as 8) (
iNumPlanets
已被初始化为8)
I then call the function load
: 然后,我将函数称为
load
:
load("radii.dat", equi_rad, pol_rad, iNumPlanets, name);
Load reads through the file in a loop and populates arrays. 加载会循环读取文件并填充数组。 I've verified that this is working correctly within the function, so there seems no point copying out this bit of code.
我已经验证了该函数在该函数中是否正常运行,因此似乎没有必要复制这段代码。 This is the prototype:
这是原型:
int load(const char* filename, double *equitoral_radii, double *polar_radii, const int iNumPlanets, char *planet_name[]);
Back in my main function, the equi_rad
and pol_rad
arrays are populated correctly and can be worked with. 回到我的主函数中,
equi_rad
和pol_rad
数组已正确填充并且可以使用。 However, when I try to printf
the name
array contents, it's just random nonsense. 但是,当我尝试
printf
name
数组内容时,这只是随机的废话。
Can anyone explain why I can successfully modify the double
arrays in a function, but not the string arrays? 谁能解释为什么我可以成功地修改函数中的
double
精度数组而不是字符串数组?
Back in my main function, the equi_rad and pol_rad arrays are populated correctly and can be worked with.
回到我的主函数中,equi_rad和pol_rad数组已正确填充并且可以使用。 However when I try to printf the name array contents, it's just random nonsense.
但是,当我尝试打印名称数组内容时,这只是随机的废话。
You need to show the code. 您需要显示代码。 Guess is you are not correctly populating
planet_name
array. 猜猜是您没有正确填充
planet_name
数组。 You might need to use malloc
(eg, planet_name[i] = malloc(LENGTH)
), and copy the string contents there. 您可能需要使用
malloc
(例如, planet_name[i] = malloc(LENGTH)
),然后在其中复制字符串内容。 Then you should have no issues. 那么您应该没有问题。 eg
例如
planet_name[i] = malloc(strlen(sourceStr)+1);
strcpy(planet_name[i], sourceStr);
Don't forget to free
each of the pointers for which you allocated data. 不要忘记
free
分配了数据的每个指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.