tags:

views:

108

answers:

3

Hi, I 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

+2  A: 

You're starting with uninitialized memory.

man memset
bmargulies
+4  A: 

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.

codaddict
Especially large negative numbers you weren't expecting
Draemon
Since the total for a word should never be a negative value perhaps lexicographical_values should be an array of unsigned int's rather than ints
Trent
Thanks a lot. This worked! I was wondering about array initialisation but didn't believe that a loop would be an elegant solution.
Ilya Biryukov
Nitpick note: the empty braces will work in C++, but for C (unless the compiler is using a language extension) there needs to be at least one const for the 1st item (the remainder will be zero-initialized), so this needs to be `int lexicographical_values[20] = {0};`
Michael Burr
A: 

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.

César Miramontes