Sun iOS
Sun iOS

Reputation: 1

char pointer in C initialized with string — can anyone explain to me each step

const char var = '1'; // or var = 'a'

I have written these two lines in Xcode 5.1.1, Command line tool--> select C

const  char * stmt_sel = "select * from Student";

printf("sql : %s",stmt_sel);

I'm confused: char accepts single char, char pointer accepting string. Can anyone explain to me about the pointer in clear and how it works in this scenario?

Upvotes: 0

Views: 60

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

A char pointer can point to a string, but it does not store it.

When you do this

const char *stmt_sel = "select * from Student";

stmt_sel contains the address of the memory location where the string is stored1, the type of the pointer allows pointer arithmetic to work, for example

printf("%s\n", stmt_sel + 7);

would print * from Student, because you moved the pointer 7 units of it's type size, and since sizeof(char) == 1, then that means 7 bytes.


1I'ts not a physical address, it's a virtual address used by the operating system and in the end it gets mapped to a hardware address.

Upvotes: 1

Related Questions