开发者

EXC_BAD_ACCESS runtime exception when accessing the structure variables->Objective C

test.h
-------
struct session {
 开发者_如何学Python   int a;
    int c;
    int b;
};
struct session* pEvent;
#import <Foundation/Foundation.h>


@interface test : NSObject {

}
-(void)set;
@end

test.m
--------

#import "test.h"


@implementation test

-(id)init{
    pEvent->a=10;
    pEvent->c='a';
    pEvent->b=20;
    return self;
}
-(void)set{

    //struct session* pEvent;
    //pEvent->a=10;
    //pEvent->c='a';
    //pEvent->b=20;
    NSLog(@"a:%d c:%c b:%d",pEvent->a,pEvent->c,pEvent->b);

}

@end

I am getting EXC_BAD_ACCESS runtime exception and the debugger points to pEvent->a when

declared in both the ways inside the init method or inside the set method.

Do i need to intialise the structure as pEvent = new session;? If declared like this I'm

getting new undeclared error. Then I tried with pEvent = [session new]; and pEvent = [[session alloc]init]; If declared like this i'm getting session undeclared error.


Try this:

struct session {
    int a;
    int c;
    int b;
} pEventStruct;
struct session* pEvent = &pEventStruct;

You got bad access as you have not allocated memory for pEvent, just declared a pointer.


For a global structure you don't want a pointer unless you malloc, so like so:

struct session {
    int a;
    int c;
    int b;
};
struct session pEvent;

Then pEvent.a = 10 to access.

A better design might be to use object-oriented patterns like singletons or a class method to access your data structure, however.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜