简体   繁体   中英

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?

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 stored 1 , 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.


1 I'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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM