0

TL;DR Why does METHOD2 below work and not METHOD1??

I'll preface this with saying that after hours of trial and error, I got the code to work. However, I am still VERY CONFUSED as to why one method works but the method that I had originally tried DOES NOT. When converting the long long (user's credit card number input) into an array, I originally wanted to use this method so that for a 15 number card, Array[15] would equal the final digit. (I know the order doesn't matter and I eventually disregarded this order and solved the problem, but it was easier for my brain to think about the remaining code.)

My original method is below, followed by the output of the array

METHOD1:

int array[count];

    //splits the digits into array
    for (int i = 1;i <= count; i++) 
    {
        array[ count + 1 - i ]=  n%10;
        n = n/10;
        printf("%i\n", array[count + 1 -i]);
    }    

And the output is this:

^crazyflier@ide50:~/workspace/hacker1 $ ./credit
Number:123456789012345
5
4196491
32764
668343280
0
20131904
28744
-2045911175
32603
1859886720
0
4198616
0
4198138
0
INVALID

However, after hours of trying to figure this out I switched the code to the following, and it works just fine!

METHOD 2:

int array[count];

    //splits the digits into array
    for (int i = 1;i <= count; i++) 
    {
        array[ i ]=  n%10;
        n = n/10;
        printf("%i\n", array[i]);
    }    

Gives the following output:

crazyflier@ide50:~/workspace/hacker1 $ ./credit
Number:123456789012345
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
INVALID

THANK YOU FOR YOUR HELP!

2
  • Assuming count is 15 (as per your example), then array has indexes 0 through 14. There is no array[15]. In both METHODS you are accessing memory that doesn't belong to array. Which is a memory leak, but does not explain the wild result in METHOD1. It would be interesting see how n and c are declared and populated. Jun 8 '16 at 22:36
  • Thank you! Changing it from i=1 to i=0, and <= to < made both methods 1 and 2 work exactly the way they are supposed to. I actually just watched the next lecture videos from the next week a couple of hours ago and had the aha moment as David talked about segmentation errors. As far as n and c, they are simply initialized as follows. long long n = GetLongLong(); int count=0;
    – crazyflier
    Jun 9 '16 at 3:07

You must log in to answer this question.

Browse other questions tagged .