Objective c 为什么这个简单的代码会导致EXC\u访问错误? #导入 类型定义结构节点{ 整数偏移量; }节点; int main(int argc,const char*argv[] { @自动释放池{ NSMUTABLEARRY*array=[[NSMUTABLEARRY alloc]init]; Node Node={111111}; NSValue*value=[NSValue值:&NodeWithObjcType:@encode(node)]; [数组addObject:value]; NSValue*structValue=[array objectAtIndex:0]; 节点*n=(节点*)[structValue pointerValue]; printf(“偏移量:%d”,n->offset); } 返回0; }

Objective c 为什么这个简单的代码会导致EXC\u访问错误? #导入 类型定义结构节点{ 整数偏移量; }节点; int main(int argc,const char*argv[] { @自动释放池{ NSMUTABLEARRY*array=[[NSMUTABLEARRY alloc]init]; Node Node={111111}; NSValue*value=[NSValue值:&NodeWithObjcType:@encode(node)]; [数组addObject:value]; NSValue*structValue=[array objectAtIndex:0]; 节点*n=(节点*)[structValue pointerValue]; printf(“偏移量:%d”,n->offset); } 返回0; },objective-c,struct,exc-bad-access,Objective C,Struct,Exc Bad Access,代码在此行崩溃:printf(“偏移量:%d”,n->offset)但是为什么呢?获取c值的正确方法是getValue:: #import <Foundation/Foundation.h> typedef struct Node { int offset; } Node; int main (int argc, const char * argv[]) { @autoreleasepool { NSMutableArray *array =

代码在此行崩溃:
printf(“偏移量:%d”,n->offset)但是为什么呢?

获取c值的正确方法是
getValue:

#import <Foundation/Foundation.h>

typedef struct Node {
    int offset;
} Node;

int main (int argc, const char * argv[])
{

    @autoreleasepool {

        NSMutableArray *array = [[NSMutableArray alloc] init];
        Node node = {111111};
        NSValue *value = [NSValue value:&node withObjCType:@encode(Node)];
        [array addObject:value];

        NSValue *structValue = [array objectAtIndex:0];
        Node *n = (Node *)[structValue pointerValue];

        printf("offset: %d", n->offset);
    }
    return 0;
}

pointerValue
不返回指向存储值的指针,它从存储
节点的内存中读取指针值(如
union{Node n;void*pointerValue;}
)。

返回c值的正确方法是
getValue:

#import <Foundation/Foundation.h>

typedef struct Node {
    int offset;
} Node;

int main (int argc, const char * argv[])
{

    @autoreleasepool {

        NSMutableArray *array = [[NSMutableArray alloc] init];
        Node node = {111111};
        NSValue *value = [NSValue value:&node withObjCType:@encode(Node)];
        [array addObject:value];

        NSValue *structValue = [array objectAtIndex:0];
        Node *n = (Node *)[structValue pointerValue];

        printf("offset: %d", n->offset);
    }
    return 0;
}

pointerValue
不返回指向存储值的指针,它从存储
节点的内存中读取指针值(如
union{Node n;void*pointerValue;}
)。

如果要添加指针并接收指针,请使用
NSValue*value=[NSValue valueWithPointer:&Node]

如果要添加指针并接收指针,请使用
NSValue*value=[NSValue valueWithPointer:&node]

如果在printf行之前检查“n”的内容会发生什么?我只是无法访问
n->offset
,但是
printf(“%d”,n)
输出
111111
。但是如果我在
节点
结构中添加另一个字段,
printf(“%d”,n)
只打印第一个字段的值。如果在printf行之前检查“n”的内容会发生什么?我只是无法访问
n->offset
,但是
printf(“%d”,n)
输出
111111
。但是如果我将另一个字段添加到
节点
结构中,
printf(“%d”,n)
只打印第一个字段的值。