Dereferencing an uninitialized pointer in Objective-C [closed] - objective-c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is happening in this code http://ideone.com/stD7VU
First I thought ok i'm using an int for a pointer and the compiler doesn't warn me. Then the 2nd block I can't understand how I can dereference a when I didnt use new. Whats happening? I don't know obj-c.
#import <stdio.h>
#implementation TestObj
int main()
{
{
int *a;
a=5;
printf("%d\n", a);
}
{
int *a;
*a=7;
printf("%d\n", *a);
}
return 0;
}
#end

First I thought ok i'm using an int for a pointer and the compiler doesn't warn me.
Actually it does. In the first block, the line
a=5;
will rise a compiler warning, specifically
Incompatible integer to pointer conversion assigning 'int *' from 'int'.
I can't understand how I can dereference a when I didnt use new
You are trying to dereference an uninitialized pointer. This is undefined behavior in C (and being Objective-C a superset of C, so it's in it), so you program could technically print the whole Divine Comedy by Dante and still be consistent with the specification.
By the way you don't need any special C construct for initializing pointers. Objective-C is a proper subset of C, so you can use malloc.
In case of objects there's a whole set of APIs dedicated to object allocation and deallocation, including new.

Related

Are pointers just the same as global variables? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
They seem to have more or less the same purpose.
they told me that pointers are just memory addresses of data locations so that instead of passing large objects and data, you just pass a number.
but i still can't see difference.
please, explain.
No, they aren't the same since you need access to the pointer to access what it points to.
Unless you make the pointer global, you can't access what it points to from everywhere.
A pointer is a type of variable that stores a memory address. They can have scope just as any other variable. A global variable is a variable with global scope, meaning it can be accessed from anywhere.
Just because a pointer is global, it doesn't mean the data in memory is global. If the data in memory is garbage collected from going out of scope (e.g. from an if statement ending or a function ending), the pointer will now point to re-purposed memory, and the value at that memory address will be unpredictable.
If anything, pointers are generally used as a way to share local variables without creating a global variable. Instead, you only pass the pointer to functions you want to share the value with.
I'm going to assume you're talking about c++. Pointers are not global unless you assign it to a variable that is global. Here is an example in c and should be the same in c++:
#include <stdio.h>
int x = 5; //Global variable
int* x_pointer = &x; //global pointer that holds the address of x
int main() {
int y = 43; //Local variable
int* y_pointer = &y; //local pointer that holds the address of y
return 0;
}
Hope this helps!

How can I get sizeof class based on NSObject [duplicate]

This question already has answers here:
Checking the size of an object in Objective-C
(6 answers)
Closed 8 years ago.
I'm new to obj-c . During these day's practices I noticed that every class based on NSObject can't have an entity like : NSObject en; in c++ but NSObject* en instead.
But, sometimes I need to know the Size of an Object.I can't simply write sizeof(en) because en is a pointer var.I can't simply use sizeof(NSObject) neither for the compiler telling me Application of sizeof to interface 'XXXX' is not supported on this architecture and platform.
I want to know if there is a way to get sizeof(NSObject) .If not,what the syntax is designed this for & any other ways to get the size.
From doc
class_getInstanceSize
Returns the size of instances of a class.
size_t class_getInstanceSize(Class cls)
Parameters cls A class object.
Return Value The size in bytes of instances of the class cls, or 0 if
cls is Nil.
But I doubt this is what you really want. Because I never found it useful and can't think a case it may be useful. (other than learning memory layout of objects and low level implementation details)
First, you should import malloc.h
If you use Non-ARC:
malloc_size(myObject);
if you are using ARC:
malloc_size((__bridge const void *) myObject));
This linker is a question similar to yours.

How do I identify the return type of a method during runtime? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
For the sake of this question, let us say that I have an Objective-C class consisting of the following methods:
- (float)method1;
- (CGPoint)method2;
- (NSString *)method3;
- (void)method4;
How can I identify the return types of all the methods above dynamically during runtime?
You can use Objective-C runtime functions to get this information, but there are limitations. The code below will do what you want:
Method method1 = class_getInstanceMethod([MyClass class], #selector(method1));
char * method1ReturnType = method_copyReturnType(method1);
NSLog(#"method1 returns: %s", method1ReturnType);
free(method4ReturnType);
Method method2 = class_getInstanceMethod([MyClass class], #selector(method2));
char * method2ReturnType = method_copyReturnType(method2);
NSLog(#"method2 returns: %s", method2ReturnType);
free(method4ReturnType);
Method method3 = class_getInstanceMethod([MyClass class], #selector(method3));
char * method3ReturnType = method_copyReturnType(method3);
NSLog(#"method3 returns: %s", method3ReturnType);
free(method4ReturnType);
Method method4 = class_getInstanceMethod([MyClass class], #selector(method4));
char * method4ReturnType = method_copyReturnType(method4);
NSLog(#"method4 returns: %s", method4ReturnType);
free(method4ReturnType);
Output:
>>method1 returns: f
>>method2 returns: {CGPoint=dd}
>>method3 returns: #
>>method4 returns: v
The string returned by method_copyReturnType() is an Objective-C type encoding string, documented here. Note that while you can tell if a method returns an object (encode string "#"), you can't tell what kind of object it is.
I'd be curious why you're interested in doing this. Especially for a new Objective-C programmer, my first inclination is to encourage you to think about whether this is actually a good design choice. For the methods you've asked about, this is pretty straightforward, but methods with more exotic return types can lead you into some trickier stuff with type encodings.

What is 'id' in the following code? in Objective C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to ask that what is that id? I don't understand what this id is. I got this code from a book and it says a generic type that's used to refer to any kind of object. Can anyone help me with this? I read it few times. Still can't get it.
void drawShapes (id shapes[], int count){
for (int i = 0; i < count; i++) {
id shape = shapes[i];
[shape draw];
}
} // drawShapes
id is an alias for an unknown Objective-C object. It can be used to declare any Objective-C object value.
In the example you have it is using an id rather than a specific class so that the code is not dependent on the class of shape.
Strictly speaking id is defined as a pointer to an objc_object struct.
typedef struct objc_object {
Class isa;
} *id;
In practical terms this means any Objective-C object.
However don't confuse this with NSObject *. While in many cases the equivalence may hold, there are classes which do not descend from NSObject but are still valid Objective-C objects (and therefore whose type can be id). One notable example is NSProxy.
In the code you posted, the id stands for the type of items that will be stored in a C static Array. In particular, the id type indicates any Objective-C object.
Anyway, I would not recommend to use C static arrays in Objective-C to contains objects of unknown type, when you can achieve the same result by using an instance of NSArray.
id means "a reference to some random Objective-C object of unknown class" an example is when you make an at property for a uibutton sometimes it will come up as id but setting it as uibutton will help xcode fill in blanks for you while your typing because now xcode knows exactly what this object is. in your situation shape could be a string or a number or something else if you were just looking at that line of code though passing anything into it could give another line a error later on.

Is there an Ultimate Guide to Pointers in Objective-C? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Ok... I understand what pointers are and how they point to a memory location where the variable is stored.
However, I still can't fully get my head wrapped around when the pointer (asterisk) is to be used and when it isn't. It's still seemingly random to me.
Does anyone have any recommendations for good tutorials on the web or book chapters that really go into detail on pointers?
Thanks!
Edit: What I'm really looking for is a detailed guide that is specific to Objective-C either in a deep website tutorial or book chapter(s). I don't think there is enough space here to fully explain it for me.
Being aware that this is tagged as Objective-C..
Take a look at here.
(Un)fortunately, the asterisk * has many different meanings depending on context. So, let's look at the relevant ones. Let us write T for some arbitrary type (say int):
T x; // variable of type x, stored somewhere in memory
T * pt; // a pointer to a variable of type x -- doesn't have a value just yet
pt = &x; // the value of pt is now the address of the variable x
So far so good. We have used the asterisk to designate a new type, namely T*, which is a "pointer to T".
But what do we do with a pointer? We can dereference it to get to the value of the variable at the address pointed to by the pointer:
T y; // another variable of type T
y = *pt; // equivalent to y = x;
*pt = 81; // equivalent to x = 81;
So, if the asterisk is part of the typename, then it designates a pointer type. If it comes before a variable name (which is itself of pointer type), then it dereferences the pointer.
[Clarification:] In C, pointers naturally go hand-in-hand with the "address-of" operator &, which is used to actually obtain a pointer to something. In Obj-C, a pointer is obtained as the result of object allocation (+ initailization): T * pt = [T new];
Beware that Obj-C offers an alternative syntax to the traditional C and C++ pointer syntax, so you may encounter pointers in other guises.[/Clarification]
(The asterisk can also be used as a binary operator of course, so you can have something like this: int x = 5; int * p = &x; int y = *p * *p;.)
Peter Hosey of Growl and Adium has posted a guide to pointers on his blog. He calls it, "Everything you need to know about pointers in C," but that's because he regards the ugly pointer aspects as belonging to C rather than Obj-C. Check it out.
I don't know of any reference beyond the Clang ARC reference that describes all the crazy modifiers you can now put on pointers in Obj-C, though. And that's not a good learning resource if you're already confused.
Assuming that C pointers have no secret to you, basically in Objective-C there are two caveats to avoid:
The NS- prefix does not always denote a class. Sometimes this is only a typedef. You have to check the reference manuals.
Dotted notation introduced in Objective-C 2.0. Despite the fact that every object is a pointer, sometimes instance variables can be accessed by myObj.myVar, instead of (more consistent for newcomers) myObj->myVar.
The ultimate guide to pointers is in Kernighan & Ritchie. They're the same in Objective-C as they are in C.