Search code examples
objective-cinteger

Hackerrank Objective-c int pointer not correct value


If I want an int of an array from an index like: "int value = ar[n]", I always getting huge integers. Which represent the max size of it (I think).

Input (stdin)

4
3 2 1 3

Code:

int main(int argc, const char * argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int n;
    scanf("%i",&n);
    int ar[n];
    
    int counter = 0;
    int tempValue;
    
    for(int ar_i = 0; ar_i < n; ar_i++){
        
       int value = ar[ar_i];
        
        if(tempValue < ar[ar_i]){
            
            counter = 1;
            tempValue = ar[ar_i];
            printf("%i", tempValue);            
        }else if(tempValue == value){
            
            counter = counter + 1;
        }
    }
    
    [pool drain];
    return 0;
}           

printf("%i", tempValue); for example gives an output "1598483120". Casting any object to (int) doesn't help.

Did I do something wrong? Or what is going on?


Solution

  • You define int ar[n], but you do not initialize it with values. Accessing uninitialized variables, as you do when writing int value = ar[ar_i] then, is undefined behaviour; this often leads to "garbage" values, though other behaviour is - of course - possible as well. The same applies to variable tempValue.

    So always initialize your variables before accessing them, e.g. with for (int i=0; i<n; i++) arr[i] = 0; and int tempValue=0.

    Note further that - if you are using objective-c - your IDE (XCode probably) might not use C but C++ for your .mm-source file; Then a variable-length-array like int arr[n] may not be supported.