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

Objective-C数组中的浮点错误行为(排除错误访问)

  •  1
  • blueberryfields  · 技术社区  · 15 年前

    我在我的一个对象上声明了一个基元数组,似乎无法从外部访问它。我是客观主义者,有什么明显的错误吗?

    头文件:

    @interface MyObject : NSObject {
        //@public <-- this shouldn't be necessary, right? I have accessors!
        float *d;   
    }
    
    @property float *d;
    

    m文件:

    @synthesize d;
    
    -(id) init {
    ...
        self.d    = (float*) malloc(sizeof(float) * n); //n > 1000
    ...
    }
    

    执行访问的位置:

    MyObject* k = [MyObject init];
    
    NSLog(@"%f",k.d[0]);
    

    我在最后一行收到了一个exc_bad_访问错误,尽管我似乎找不到正确的原因。有人看到我丢失的东西吗?

    3 回复  |  直到 15 年前
        1
  •  9
  •   Garrett    15 年前

    你需要分配你的对象!

    MyObject *k = [[MyObject alloc] init];
    
        2
  •  1
  •   JeremyP    15 年前

    我编译并运行了以下代码版本:

    @interface FloatClass : NSObject
    {
        float* d;
    }
    
    @property float* d;
    
    @end
    
    @implementation FloatClass
    
    @synthesize d;
    
    -(id) init
    {
        self = [super init];
        if (self != nil)
        {
            d = malloc(sizeof(float) * 10);
        }
        return self;
    }
    
    @end
    
    int main(int argc, char *argv[])
    {
        NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    
        FloatClass* k = [[FloatClass alloc] init];
        NSLog(@"%f", k.d[0]);
    
        [pool drain];
    }
    

    它运行良好,打印了0.00000。所以我认为你没有给我们看的代码有问题。

    如果我这样做 k = [FloatClass init] 我收到一个nsInvalidargument异常。

    Nb 2。确保init方法返回self。

        3
  •  0
  •   fbrereto    15 年前

    属性定义应为:

    @property float* d; // missing the '*'