代码之家  ›  专栏  ›  技术社区  ›  Klinki

Hackerrank Objective-c int指针值不正确

  •  1
  • Klinki  · 技术社区  · 8 年前

    4
    3 2 1 3
    

    代码:

    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);例如,输出“1598483120”。 将任何对象强制转换为(int)都没有帮助。

    我做错什么了吗?或者发生了什么?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Stephan Lechner    8 年前

    您定义 int ar[n] ,但不使用值初始化它。访问未初始化的变量,就像编写时一样 int value = ar[ar_i] 然后,是未定义的行为;这通常会导致“垃圾”价值观,当然也可能有其他行为。这同样适用于变量 tempValue .

    因此,在访问变量之前,请始终初始化变量,例如 for (int i=0; i<n; i++) arr[i] = 0; int tempValue=0 .

    进一步注意,如果您使用objective-c,您的IDE(可能是XCode)可能不会使用c,而是使用c++ .mm -源文件;然后是一个可变长度数组,如 int arr[n] 可能不受支持。