Best arrays questions in July 2011

What does an expression like arr[''hi there"] imply?

17 votes

If a=3 and b=5 what does this imply?

printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]);

I know that arr[4] means *(arr+4) so I need to know what does an expression like "hi there" imply?

EDIT - Question in probably clearer terms:

When a string is used as an array subscript what value does it convey ?

Why is output of above Hello! how is this? super ?

That implies, the printf becomes equivalent to this:

printf("Hello! how is this? %s\n", "super");

which will print:

Hello! how is this? super

Online demo : http://ideone.com/PVzUP

Explanation:

When we write char s[]="nawaz; and then s[2] means 3rd character in the string s. We can express this by writing "nawaz"[2] which also means 3rd character in the string "nawaz". We can also write 2["nawaz"] which also means 3rd character in the string. In your code, the printf uses the last form, i.e of the form of 2["nawaz"]. Its unusual, though.

So a["Ya!Hello! how is this? %s\n"] means 4th character in the string (as the value of a is 3), and if you add & infront of a then &a["Ya!Hello! how is this? %s\n"] returns the address of the 4th character in the string, that means, in the printf it becomes equivalent to this:

Hello! how is this? %s\n

And I hope you can interpret the rest yourself.

How are static arrays stored in Java memory?

16 votes

So in a language like C, memory is separated into 5 different parts: OS Kernel, text segment, static memory, dynamic memory, and the stack. Something like this:

Memory Layout

If we declared a static array in C, you had to specify it's size beforehand after that would be fixed forevermore. The program would allocate enough memory for the array and stick it in the static data segment as expected.

However I noticed that in Java, you could do something like this:

public class Test {
        static int[] a = new int[1];

        public static void main( String[] args ) {
                a = new int[2];
        }
} 

and everything would work as you'd expect. My question is, why does this work in Java?

EDIT: So the consensus is that an int[] in Java is acts more similarly to an int* in C. So as a follow up question, is there any way to allocate arrays in static memory in Java (if no, why not)? Wouldn't this provide quicker access to such arrays? EDIT2: ^ this is in a new question now: Where are static class variables stored in memory?

In java any time you use the word new, memory for that object is allocated on the heap and a reference is returned. This is also true for arrays. The int[] a is just the reference to new int[1]. When you do new int[2], a new array is allocated and pointed to a. The old array will be garbage collected when needed.

Removing elements from an array whose value matches a specified string

6 votes

I have an array that looks like this:

Array ( [0] => Vice President [1] =>   [2] => other [3] => Treasurer )

and I want delete the value with other in the value.

I try to use array_filter to filter this word, but array_filter will delete all the empty values, too.

I want the result to be like this:

Array ( [0] => Vice President [1] =>   [2] => Treasurer )

This is my PHP filter code:

function filter($element) {
  $bad_words = array('other');  

  list($name, $extension) = explode(".", $element);
  if(in_array($name, $bad_words))
    return;

  return $element;
}

$sport_level_new_arr = array_filter($sport_level_name_arr, "filter");

$sport_level_new_arr = array_values($sport_level_new_arr);

$sport_level_name = serialize($sport_level_new_arr);

Can I use another method to filter this word?

foreach($sport_level_name_arr as $key => $value) {

  if(in_array($value, $bad_words)) {  
    unset($sport_level_name_arr[$key])
  }

}

Array in success function undefined

2 votes

Why does this code

for(var i = 0; i < array.length; ++i) {
    array[i]["bla"] = "check";
}

work perfectly, whereas the array is here, according to firebug, undefinied:

for(var i = 0; i < array.length; ++i) {
    $.ajax({
        type: "POST",
        url: "my url",
        data: "data here",
        success: function() {
            array[i]["bla"] = "check";
        }
    });
}

How can I fix that issue?

Due to how closures work, the value of i is always going to be equal to array.length in the callback, because that's what it equals after the loop is done (after all, i < array.length is false). And that position is always undefined. You need to re-bind i inside the loop to make the current value "stick". Unfortunately the only way to do this in standard JS is to use yet another function, for instance:

for (...; i++) {
    (function(boundI) {
        // boundI is now bound to the current value of i in the current scope
        // If you want, you can call boundI just "i", but make sure you understand
        // how scopes work in JS before you do.
        $.ajax({
            ...
            success: function() {
                array[boundI]["bla"] = "check";
            }
        });
    })(i); // pass in the current value of the loop index which gets bound to boundI
}