I am learning about pointers in C++. When initializing pointers, for example,
double* pvalue1 = nullptr;//okay
char* pvalue2 = nullptr; //only this says, "0x00000000 <Bad Ptr>" (in the watch window of Visual C++ 2010)
int* pvalue3 = nullptr; //okay
Why does only the char
type pointer give Bad Ptr while other pointer types don't?
I don't care about the pointed-to values at the moment. I am not dereferencing them (that's why there are those errors above). I am just looking at the watch window for those three pointers.
In your case int *ptr = NULL is completely redundant as you could just write int *ptr = a as Vlad has already said, but more generally it is a good idea to initialise pointers to NULL because if for some reason you have an error in your code and you need to debug it, it is a lot easier to debug what is happening to the ...
The data type of pointer is needed when dereferencing the pointer so it knows how much data it should read. For example, dereferencing a char pointer should read the next byte from the address it is pointing to, while an integer pointer should read 4 bytes.
What is the difference between char and char*? char[] is a character array whereas char* is a pointer reference. char[] is a specific section of memory in which we can do things like indexing, whereas char* is the pointer that points to the memory location.
We can create a character pointer to string in C that points to the starting address of the character array. This pointer will point to the starting address of the string, that is the first character of the string, and we can dereference the pointer to access the value of the string.
For most pointer types, the Watch window in Visual Studio displays the value of the pointer (the address to which it points), and allows you to access the pointed-to value by expanding the + icon. So for a null pointer to, let's say, int
, it will simply show null
or 0x00000000
or something like that.
char*
s are handled differently. Here, the Watch does not show the pointer value at all, but directly interprets the pointed-to data as a NUL
-terminated string and prints that. This of course means that a null char*
does not give meaningful results, hence the Bad Ptr
.
In other words, Watch itself automatically does the dereferencing for char*
pointers (and only for those).
Presumably, whatever you're using to display the pointer values will also display whatever string a char*
pointer points to, since such pointers are sometimes used to point to strings.
In this case, being null, it doesn't point to any string, so whatever is displaying it tells you that instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With