Reck
Reck

Reputation: 81

objective-c - Why can I assign values to pointers?

I understand pointers work with addresses and not the data itself. This is why I need to use the address-of (&) operator below as I need to assign the address of num to the pointer and not the actual value of num (40).

int num = 40;
int *numPtr = #

Therefore i'm confused as to why I can do this.

NSString *str = @"hello";

I've created a pointer str but instead of giving it an address i'm able to assign it some data, a literal string.

I thought pointers could only hold memory addresses so why am I able to directly assign it some data?

For someone trying to get their head around pointers and objects this is very confusing.

Upvotes: 1

Views: 158

Answers (3)

orkoden
orkoden

Reputation: 20006

C does not have strings. Usually char arrays are used to represent them.

NSString *str = @"hello";

can be thought of as short hand (literal) for:

char charArray[] = "hello";
NSString *str = [[NSString alloc] initWithBytes:charArray length:sizeof(charArray) encoding:NSUTF8StringEncoding];   // disregard character encoding for this example

or

unichar bla[] = {'h', 'e', 'l', 'l', 'o'};
str = [[NSString alloc] initWithCharacters:bla length:sizeof(bla)];

So an object is created and thus you need a pointer.

Upvotes: 0

Jonathan.
Jonathan.

Reputation: 55574

There is a reason you put an @ before string literals (when you want an NSString and not a C string) in objective-c

@"String" is basically equivalent to [NSString stringWithCString:"string"] which returns a pointer to an NSString object containing the value "string"

It is the same way 1 is a c type integer, but @1 is a NSNumber representing the value of 1. If you see an @ it means "this is shorthand for creating an object". (@[] for NSArrays, @{} for NSDictionarys, @(), @123, @YES, @NO for NSNumbers, and @"" for NSString)

Upvotes: 2

rckoenes
rckoenes

Reputation: 69469

No you are not assigning a literal string to it, @ makes a NSString object with the string value hello.

In most C languages strings are just an array of char, where char is a primitive type like int like in your example.

Upvotes: 4

Related Questions