Monday, 12 August 2013

Differences between int/char arrays/strings

Differences between int/char arrays/strings

I'm still new to the forum so I apologize in advance for forum - etiquette
issues.
This is in c.
I'm having trouble understanding the differences between int arrays and
char arrays.
I recently wrote a program for a project euler problem that originally
used a char array to store a string of numbers, and later called specific
characters and tried to use int operations on them to find a product. When
I used a char string I got a ridiculously large product, clearly
incorrect. Even if I converted what I thought would be compiled as a
character (str[n]) to an integer in-line ((int)str[n]) it did the exact
same thing. Only when I actually used an integer array did it work.
Code is as follows
for the char string
char str[21] = "73167176531330624919";
This did not work. I got an answer of about 1.5 trillion for an answer
that should have been about 40k.
for the int array
int str[] = {7,3,1,6,7,1,7,6,5,3,1,3,3,0,6,2,4,9,1,9};
This is what did work. I took off the in-line type casting too.
Any explanation as to why these things worked/did not work and anything
that can lead to a better understanding of these ideas will be
appreciated. Links to helpful stuff are as well. I have researched strings
and arrays and pointers plenty on my own (I'm self taught as I'm in high
school) but the concepts are still confusing.
Thank you!
Side question, are strings in c automatically stored as arrays or is it
just possible to do so?

No comments:

Post a Comment