I开发者_StackOverflow am learning C language and I am facing a problem I don't seem to be able to resolve on my own. I have a simple loop where I add up ascii values of all characters in each word.
char char_array[100];
int lexicographical_values[20];
int i, j = 0;
for( i = 0; i <strlen(char_array); i++) {
if(char_array[i] == ' ')
j++;
lexicographical_values[j] += (int)char_array[i];
}
Then, if I output the lexicographical_values array in a loop
printf("%d word is: %d \n", i, lexicographical_values[i]);
I get correct figures for each word (ex: dd = 200 and so on)
But if I actually look at each element's value in the array, I get big numbers that are far from being correct.
The question is, how do I get correct values and how does printf obtain the correct values?
Thanks
You have not initialized the lexicographical_values array. You can initialize it by doing:
int lexicographical_values[20] = {};
Every time you see big numbers in the output, check for uninitialized variables.
You're starting with uninitialized memory.
man memset
You have not initialized the char_array with anything, so most likely it has garbage (depends on compiler options and platforms) so, you do a strlen(char_array)
and at this point we're not sure what we're going to get out of it. If you initialize it with 0s (like: char char_array[100] = {0};
then strlen
will return 0 and you'll never enter the loop.
Maybe you're looking for sizeof()
here?
Oh, yes, forgot to mention that you need to initialize the second array also as was already pointed out.
精彩评论