AgileVortex
AgileVortex

Reputation: 83

Create char from char* that includes escape character

Consider the following char* example:

char* s = "\n";

How can this be converted into a single char that represents the new line character like so:

char c = '\n';

In addition to processing newlines I also need to be able to convert any character with an escape character preceeding it into a char. How is this possible?

Upvotes: 7

Views: 553

Answers (4)

GreenMatt
GreenMatt

Reputation: 18570

As others said, the newline is actually only one character in memory. To get a single character from a string pointer, you can access your pointer as if it is an array (assuming, of course, that there is memory allocated for the string pointed to):

char* s = "\n";
char  c = s[0];

Upvotes: 2

pmg
pmg

Reputation: 108978

char c = *s; works.

The '\n' inside the string is only two characters in source form: after compiling it is a single character; the same for all other escape character.

The string "fo\111\tar", after compiling, has 7 characters (the 6 visible in the source code ('f', 'o', '\111', '\t', 'a', and 'r') and a null terminator).

Upvotes: 9

JonH
JonH

Reputation: 33143

Dereference it:

char* s = "\n";
char c = *s;

Upvotes: 3

Heisenbug
Heisenbug

Reputation: 39164

Do you mean something like that?

char * s = "\n";
char c = *s;

Upvotes: 1

Related Questions