aspose file tools*
The moose likes C / C++ and the fly likes How the pointer represent in the case of String and Char Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Languages » C / C++
Bookmark "How the pointer represent in the case of String and Char" Watch "How the pointer represent in the case of String and Char" New topic
Author

How the pointer represent in the case of String and Char

J Shankar
Greenhorn

Joined: Mar 20, 2012
Posts: 3

Consider *ptr = "I am";
ptr = i am a string;
printf ("%c, %s", *ptr, ptr);

output:: I i am a string

Please help me to understand "how the pointer is represented for Char and String" in the above scenario.

Thanks in advance.
Anthony Aj Williams
author
Ranch Hand

Joined: Jun 10, 2011
Posts: 56
J Shankar wrote:Please help me to understand "how the pointer is represented for Char and String" in the above scenario.


A string literal produces a "null-terminated string" in the generated code. This is a series of characters followed by a zero byte. So, "I am a string" takes up 14 bytes: one for each of the 13 characters in the string, plus a final zero byte.

A pointer holds an address. On 32-bit architectures this is usually a single 32-bit value which the processor can use to identify the location of some data. If you say



Then ptr is declared as a pointer to char. In this case, the pointer holds the address of the first character in the string, I. Since the subsequent characters in the string are stored at adjacent locations, your code can find the rest of the string from this pointer to the first character, checking each character in turn until it finds the zero byte at the end of the string --- this is why the string is null-terminated.

The pointer-dereference operator * retrieves the value stored at the pointed-to location. Since ptr is a pointer-to-char, the value stored is a character, in this case the [b]I[/bb] that is the first character in the string.

When you print things with printf, %c says to print a character, and %s to print a null-terminated string identified by a pointer to its first character, so you get the I I am a string output you describe.


Author of C++ Concurrency in Action http://www.stdthread.co.uk/book/
just::thread C++11 thread library http://www.stdthread.co.uk
Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976
 
 
subject: How the pointer represent in the case of String and Char
 
Similar Threads
Help with my first Objective-C class
byte array to object casting
char* equivalent of JNI?
Only fun forwards for fun ...
case of two equal object