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

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!

Related

How does Objective C deals with primitive __block variables on stack when block is copied?

I have the following code under ARC:
-(void) foo {
__block int spam = 42;
self.myProperty = ^{
spam++;
}
self.myProperty(); // Increment first time
}
-(void) bar {
self.myProperty(); // Increment second time
}
When "Increment first time" is called, ObjC uses pointer to spam (which resides on stack) to increment it, right?
After it, foo stack is thrown out, so pointer is not valid anymore.
What will bar do? What should happen when I call it?
Everything is clear about objects, since they are created on heap and block copying (which takes place in the moment of property assignment) leads to retain call. But what is about auto vars?
I can use debugger to find the answer, but I want to fully understand it: which part of Objc/clang specification covers that?
Update: A used "&" to get address of my variable and found that address get changed in the moment I assign block to my property (actually at the moment when block is copied). I believe that is the moment from my variable was moved from stack to heap.
-(void) foo {
__block int spam = 42;
int* addrOfSpam = &spam;
*addrOfSpam = 43; // OK, spam = 43 now
self.myProperty = ^{ // The moment when spam is moved from stack to heap
spam++;
};
*addrOfSpam = 44; // Fail, spam not changed and 'addrOfSpam' points to nowhere
spam++; // Spam looks like auto/stack var here, BUT IT IS NOT!
// It is on heap now, and "spam" is changed by compiler to:
// *(newAddressOfSpamInHeap_OnlyCompilerKnowsWhere)++;
}
The salient passage in the doc is here. (boldface added by me)
__block variables live in storage that is shared between the lexical scope of the variable and all blocks and block copies declared or
created within the variable’s lexical scope. Thus, the storage will
survive the destruction of the stack frame if any copies of the blocks
declared within the frame survive beyond the end of the frame (for
example, by being enqueued somewhere for later execution). Multiple
blocks in a given lexical scope can simultaneously use a shared
variable.
The block qualifier places the variable in a scope that will persist at least as long as the block that refers to it. So the first and second invocations of the block are identical with respect to the variable. After the second call, spam should equal 44.
First of all, __block is a storage qualifier for variables, and it the same way for all types of variables. Whether it's a variable of primitive type, pointer-to-object type, or whatever (by the way, a variable cannot have "object type"); doesn't matter. Variables of all types normally reside on the stack if they are local variables of a function. Referring to a local variable of pointer-to-object type after its scope has exited equally results in undefined behavior.
About your question, the answer is that __block variables are not only stored on the stack. They can also be stored on the heap. How it works is an implementation detail but it's guaranteed by the specification to be valid to be used in all the blocks that capture it.
If you want to know how it is actually implemented, you can read Clang's Block implementation specification (although I think there are some typos). Essentially, when you have a __block variable, you actually have a data structure, where the variable is a field. And the data structure also has a pointer to keep track of where the current version of itself is. Accesses to the variable are implicitly translated by the compiler to access it through these levels of indirection.
Just like with blocks, this data structure starts out on the stack for optimization, but can be "moved" to the heap (it gets moved the first time any block that captures it gets moved to the heap, because that's when its lifetime might need to exceed the scope it was created in). When it's "moved" to the heap, the pointer that says where it is is updated, so that people will know to use the new copy. This data structure, when in the heap, is memory-managed by a system of reference counting.
Blocks that capture __block variables have a copy of the "current version" pointer, which is updated when the data structure is moved, so they know where to access the variable both before and after the move.
About your tests, you have to be really careful about taking the address of a __block variable, because the location of the variable moves over its lifetime! (something that doesn't usually happen in C).
When you first take the address of spam, it is still on the stack, so you have the address of the stack version of it. spam is captured in a block which is then assigned to the property myProperty whose setter copies the block, moving it to the heap and also moving spam to the heap. addrOfSpam still points to the stack version of the variable which is no longer the version being used; using it to change the integer is changing the wrong version of the variable, because everyone is using the heap copy now.

Dereferencing an uninitialized pointer in Objective-C [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
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.

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.

Why is stop a BOOL pointer in enumerateObjectsUsingBlock:? [duplicate]

This question already has an answer here:
What is the BOOL *stop argument for enumerateObjectsUsingBlock: used for?
(1 answer)
Closed 9 years ago.
I understand what the stop parameter is for, but I'm curious about why this is a BOOL * instead of just a BOOL. Is it because the value itself needs to exist outside of block scope, so that enumerateObjectsUsingBlock: has access to the value potentially assigned to it by the block itself?
To answer your question (though it looks like a dupe) the block needs to tell its caller to stop enumerating if it's found what it's looking for. There are two choices in C:
return YES to continue or return NO to stop.
Set a variable in the caller's scope, hence the BOOL *.
Apple chose the second approach, although I think the first approach is both simpler (one less parameter) and more intuitive.
It cannot be just BOOL as that only sets the local copy of the variable, not the variable in the caller's scope.

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.