Thread: Array shifted when initializing variable

  1. #1
    Registered User
    Join Date
    Sep 2012
    Posts
    9

    Array shifted when initializing variable

    I'm working on Project Euler 22. I think I got the logic and my code is a step away from the answer. But something creepy is going on.

    Basically I have four functions: "read" to read the input of names, "swap" to swap two character strings, "sort" to sort an array of character strings in alphabetical order, "worth" to calculate the worth of a name.

    I ran into two troubles:

    (1) If you notice, my "sort" function actually sort the array in reversed alphabetical order. When I tried "if(strcmp(names[j-1],names[j])>0)", it gives "Illegal instruction: 4". Why is that so?

    I can still continue with the reversed sorting. But the second problem is weirder.

    (2) At the very last step, I need to define an integer "sum" to record the total name scores. But when I defined "int sum=0", the array names[] is shifted! names[1] becomes names[0], names[2] becomes names[1], and so on. How did this happen?
    Attached Files Attached Files
    • File Type: c 22.c (1.1 KB, 95 views)

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I expect the shift downward was caused by your sort function. j=0 is OK, but then you start comparing and swapping j with j-1. j-1 is array[-1], so start your loop with j=1, instead of j=0. Your sort function doesn't "bubble up" it "settles downward".

    The strcmp line of code worked fine for me, but that j-1 problem may cause some sort of error or warning to appear.

  3. #3
    Registered User
    Join Date
    Sep 2012
    Posts
    9
    Ah, stupid mistake. It does work now, thanks!

    I don't completely get the mechanism though. Why exactly the array is shifted when I initialized "int sum=0"?

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Short answer: When you're messing with undefined behavior, like accessing arrays at negative indexes, all bets are off and anything can happen.

    As Salem's signature says:

    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Initializing array of variable size
    By Anton in forum C Programming
    Replies: 11
    Last Post: 11-23-2011, 07:51 AM
  2. Problem with initializing tm * variable.
    By PaulBlay in forum C Programming
    Replies: 2
    Last Post: 04-21-2009, 08:08 AM
  3. initializing of strucutre variable
    By rajkumarmadhani in forum C Programming
    Replies: 9
    Last Post: 11-27-2007, 11:04 PM
  4. problem with initializing a variable
    By Junktyz in forum C Programming
    Replies: 3
    Last Post: 06-27-2007, 08:46 AM
  5. different way of initializing variable?
    By The Gweech in forum C++ Programming
    Replies: 3
    Last Post: 09-06-2001, 06:44 PM