• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How the pointer represent in the case of String and Char

 
Greenhorn
Posts: 3
C++ Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
author
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
You will always be treated with dignity. Now, strip naked, get on the probulator and hold this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic