although the title seems like I am simply printing an array, it is not quite that. Here is the code:
#include <stdio.h>
int main(int argc, const char * argv[]) {
char planets[7][7]={"Mercury", " Venus", " Mars", "Jupiter", " Saturn", " Uranus", "Neptune"};
float weights[7]={(200*37.8*0.01),(200*90.7*0.01),(200*37.7*0.01),(200*236.0*0.01),(200*91.6*0.01),(200*88.9*0.01),(200*112.0*0.01)};
for (int i=0; i<7; i++) {
printf("%s: %3.1f\n",planets[i], weights[i]);
}
}
My goal here is to print
Mercury: xxx.x
Venus: xxx.x
etc.
However, my code prints this:
Mercury Venus MarsJupiter Saturn UranusNeptune\365\277\357\376: 75.6
Venus MarsJupiter Saturn UranusNeptune\365\277\357\376: 181.4
MarsJupiter Saturn UranusNeptune\365\277\357\376: 75.4
Jupiter Saturn UranusNeptune\365\277\357\376: 472.0
Saturn UranusNeptune\365\277\357\376: 183.2
UranusNeptune\365\277\357\376: 177.8
Neptune\365\277\357\376: 224.0
What is that, why is it printing the whole of my array the whole time, what are the numbers like \\365\\277\\357\\376 doing at the end? I am just so confused.
The problem with your code is that you are not assigning enough 'space' in your planets
array to hold the given names!
For example, the string literal, "Mercury"
is actually an array of eight char
elements: the seven letters plus the NUL
terminator (all strings in C
should have this 'zero-byte' terminator signal and the compiler will automatically add one to any given string literal/constant).
Simply change your planets[7][7]
to planets[7][8]
and the code will work.
EDIT: What you are seeing in your output is an example of the dreaded Undefined Behaviour ! Because there is no NUL
terminator in each string, the printf
call keeps printing extra characters after the 'end' of the planet's name, until it finds a char
that is zero. Your seven planet names are in contiguous memory, so, on each loop, the printf
'overruns' into the next planet's name. After reaching the end of "Neptune" it then starts interpreting memory that was not defined as char
data as individual bytes - and neither you nor I can really predict what such memory values will be: hence Undefined Behaviour.
Make it char planets[7][8]
. When you set array size to exact number of letters in strings there is no place left for null
symbol. So printf
do not know where your strings end.
试试这个,它应该可以工作:
char* planets[7]={"Mercury", " Venus", " Mars", "Jupiter", " Saturn", " Uranus", "Neptune"};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.