Hi, i have just started understanding the concept of pointers and had a doubt which does not solidify my understanding about pointers.
let us consider an example
int x=10;
int y*=&x;
printf("value in y is address of x%lu",y);
char *a="hi how are you";
printf("why i dont get address?%s",a);
first i declare 'y' as a pointer to int and to get the address of 'x' if i print 'y' directly and the value stored in x if y is dereferenced.
My doubt is 'a' is a char pointer pointing to a string constant and when i print 'a', i get the the string constant and not address where it is stored.
Actually where is the string stored and how can i get the address.
char* is treated as C string. A C string is just an array of characters terminated by a null-character. To pass %s into the printf format means to treat it as a C string and to print characters out of the array until it reaches a null character.
If you want the value of the pointer, use %x or %p.
Also, don't use C strings. It's been established that they generally suck except for when it's certain the string will *not* contain multiple null values.
thanks @computerquip.. that explanation really clarified my doubt :)
Also, don't use C strings. It's been established that they generally suck except for when it's certain the string will *not* contain multiple null values.... So what to use instead of C strings
Well, there are *tonnnnnnnns* of alternatives. C++ provides it's own solution called std::string. D strings are literally just an array of characters with a length (since every array tracks its length).
If I pass back a string in a C API, I will sometimes use a basic C string (generally because I use std::string by default which provides the c compatible string with c_str()). But you can't use a C string for a bunch of other purposes such as holding a networking packet, handling a binary file, and so on. std::string has no issues with this because it internally uses a length and doesn't restrict itself to iterating until a null character. Thus, you'll sometimes find people using std::string to hold just about anything. std::string is also rather similar to std::vector. It's internally contiguous, it's dynamically allocated, it reallocates when needed, and even has a bunch of the same functions. The difference is simply how people interact with it and minor optimizations used when handling strings.