David Evans
David Evans

Reputation: 213

Converting char array into NSString object

As per my assignment I have to take in input from a user via a console to be used with NSString.

At the moment I have

char* name[100]; // declaring char array
NSString* firstName; // declaring the NSString

printf("Please enter first name \n");
printf("=> ");
scanf("%s", &name);

firstName = [NSString stringWithCString:name encoding:NSASCIIStringEncoding];

This works, however I am getting this warning

Incompatible pointer types sending 'char [100]' to parameter of type 'const char '

I don't want to be having these errors coming up in the code, I would like to also mention I'm using Xcode 4.2.

Can anyone explain to me why I'm getting these errors, and if I can possibly overcome them?

Many thanks in advance!

Upvotes: 11

Views: 19456

Answers (2)

Jaime
Jaime

Reputation: 471

As printed with NSLog is assigned to initialize a NSString.

NSLog(@"%s", arrayChar);
NSString *str = [NSString stringWithFormat:@"%s", arrayChar];
NSLog(@"Array to String: %@",str);

Upvotes: 6

mvds
mvds

Reputation: 47134

Change this:

char* name[100];

to

char name[100];

The first form creates an array of 100 pointers to char. The second one creates an array of 100 char elements. What might be confusing, is that name in that last case, is in fact a pointer, pointing to the first of these 100 char elements.

Upvotes: 13

Related Questions