Pointers c++. Difference between p and p* [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I don't understand what it is supposed to print when it says cout << x.
and also when it says if ( *x==*y) that means that the letters should be equal or the positions( well of the position is equal than the letter is too).

I don't understand what it is supposed to print when it says cout << x.
Since x is of type char*, it is treated like a null-terminated C string on printing. If you print a pointer into the middle of a string, the suffix of the string is printed:
const char *str = "ABCDEFG";
const char *ptr = str + 3;
cout << ptr; // prints DEFG
when it says if ( *x==*y) that means that the letters should be equal or the positions
* in this context means "the value pointed to by ...", i.e. the letters should be equal, not the positions.

When you say cout << x it's supposed to print out the whole char array. Let's say that char *x = "Something" . If you enter cout << x , the output will be: Something . The * sign is the dereference operator and it's used to dereference a pointer(in other words to get the value of the pointer). So if you have char *x = "Something" and char *y = "Some other thing" and if you want to compare the first characters of those char arrays,you would use if(*x == *y) . So dereferencing a char array gets the first char. cout << *x the output will be: S.

Related

C++ Pointing to a dynamically created memory [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Let me preface this by saying I am a c++ rookie, completely new and learning in school right now. One question I am stumped on is dynamically created memory and how to point back to it. For the assignment I have, I created the memory, printed in the console, then my task is to point back to dynamically created memory that I made at the beginning of the assignment. How do I do that? I must have to create a temporary variable or reference variable of some sort, but I'm just unsure of how to.
// Task 1
//int *p;
int j = 18;
int *p = new int(2);
cout << "Dynamically created integer: " << *p << endl;
*p = j;
cout << "Named integer: " << *p << endl;
cout << "Return to dynamically created integer: " << *p << endl;
delete p;
That second to last line where I have the *p, that is incorrect, I just need to point back to the 3rd line of code somehow. Thank you!
You have a slight misunderstanding of how pointers work. We'll correct it here.
*p = j;
You think that this changes p to point to j. It does not. But let's proceed.
cout << "Named integer: " << *p << endl;
You are now thinking that this shows what p is pointing to now. And on the next line you want p to point to what it was, before.
Except that p is always pointing to the same thing, all the time. This line:
*p = j;
This does not point p to j. This sets the value that p points to, to the value of j. This is a very subtle difference. To change p to point to j, the correct syntax would be:
p = &j;
However, at this point, it becomes logically impossible to restore the original pointer. You have to save it first:
int *old_p=p;
p = &j;
Then, after you print what's p is pointing to now, you can simply restore it:
p=old_p;
And now the second print statement will show the original value that p was pointing to.
From my understanding, you're trying to get the memory location of j, for that you can use the "address of" ( & ) operator such as 'std::cout >> "memory address of j = " >> &j >> '\n';'

Printing memory address of pointers to different primitive data types in C++ [duplicate]

This question already has answers here:
How to print the address of char array
(1 answer)
cout << with char* argument prints string, not pointer value
(6 answers)
Why does the index of a `char **` type give the whole string?
(2 answers)
Closed 2 years ago.
In C++ could someone clarify
1- In he following code, printing char* is displayed as bunch of random characters, but printing string* is just an integer address? Why so?
int * intptr;
char * charptr;
std::string * stringptr;
float * floatptr;
//printing
std::cout << intptr << " , " << charptr << " , " << stringptr << " , " << floatptr << "\n";
output:
0x7ffeea2f1a60 , ���� , 0x7ffeea2f1a48 , 0x1092d13d4
2- charptr is a pointer variable painting to part of memory that contains a character. Just for curiosity, how do you print the address of charptr?
3- While reading different sources, I came across to this: "The different printing is because of the functions (i.e. a const char *) that treat that memory as a sequence of characters". Could someone expand this answer w.r.t the above code?
char* is special with regard to printing. The reason is the historical legacy of C, where strings are represented as arrays of characters. So most of the time given a char* what you want to do is print the characters it points at.
I don't think you mean print the address of charptr (that would just be cout << &charptr), I think you mean print the address which is the value of charptr. The way to do that is to cast the address to void* before printing it.
cout << static_cast<void*>(charptr);
Your third question is essentially what I explained in the first paragraph above.

Why does printing a char* give a string rather than an address? [duplicate]

This question already has answers here:
Why is address of char data not displayed?
(8 answers)
Closed 6 years ago.
I'm going through the basics of learning C++, but keep hitting a wall when trying to decipher the following about chars and pointers. Included are line comments giving my current understanding of what's going on. Given that I have code like below:
using namespace std;
int main()
{
//String literal is an array of chars
//Array address gets assigned to a ptr of char
char myletters[] = {'h','i'};
char* lp = myletters;
cout << *lp << endl;
//Logically equivalent to above statements
char* letters2 = "hi";
cout << *letters2 << endl;
//String literal turns into array of chars
//Array of chars gets assigned to a ptr of chars
//Each ptr of chars gets stored into letters array
char* letters[] = {"hi","hello"};
cout << *letters << endl;
}
My output will be:
h
h
hi
My question is: when I use the final cout to print the contents of *letters, why do I get the string "hi" rather than the address of "hi" or the address of the first character in "hi"? I get that the first uses of cout are printing a char, and that the last cout is printing a char*, but I'm still wondering why it prints the complete string rather than the address as I would generally expect from a pointer.
Thanks kindly.
the << operator has a special definition for char* that prints the C-string it refers.
In your case, *letters has char* type (being letters a char*[], same as char**) and not char as *lp have.

How to store a string into an an array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to store this string into an an array.
space= 0
A,a =1
B, b =2
C , c = 3
.
.
Z, z= 26
string myArray[26] =
{ "A", "B", "C", "D",”E”,”F”,”G”,”H”,”I”,”J”,”K”,”L”,”M”,”N”,”O”,”P”,
”Q”,”R”,”S”,T”,”U”,”V”,W”,X”,”Y”, ”z” };
for (int i = 0; i < myArray; i++)
{
myArray[] = myArray[i]
cerr << myArray[i] << endl << endl;
}
Is that how to get each character with number?
What you've got is an array of strings, not an array of characters. A string is a container of characters, in the sense that it is capable of holding multiple characters. Your task can be solved with one or two strings, depending on your design preferences (see below).
A, a =1
B, b =2
You are placing two characters per position. However, strings cannot hold more than one character at a single index. If you need both the upper and lower case character to occupy the same spot, you need to make either two strings, or two spots.
Here is the first approach (two strings):
string upper = " ABCDEF...";
string lower = " abcdef...";
int pos = ...; // The desired position
cout << upper[pos] << endl;
cout << lower[pos] << endl;
Here is the second approach (two positions):
string pairs = " AaBbCcDdEeFf...";
int pos = ...; // The desired position
cout << pairs[2*pos] << endl; // Upper
cout << pairs[2*pos+1] << endl; // Lower

Unable to understand struct to char* conversion [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have defined a struct data and assigning it to a char*. However the size of strlen function always gives result as 1 and cout doesn't show anything. Here is my code:
struct data
{
int x;
int y;
};
int main()
{
data d;
d.x = 10;
d.y = 20;
char *ch = (char*)&d;
cout <<"Length:" strlen(ch) << endl;
cout << ch << endl;
}
The output is:
Length: 1
Please help me in understanding what's going on ?
The strlen function counts all bytes in the passed string until it finds the character '\0'. This character is the same as the integer 0.
So what the call to strlen is count the number of bytes until it finds a zero, and in your case the zero happens to be in the second byte of the structures binary representation, meaning that the "string length" is one.
The only thing that you can deduce from this is that you are on a little endian system. Other than that, the call is undefined behavior as the "string" isn't actually a string.
The reason it returns 1 is because you are treating the struct as a char array. Doing this you are re-interpreting the contents of the struct - the integer 10, which is probably stored in memory as 0x0A000000 - as a string. And that yields a length of 1 (only 1 non-zero value before a null-character in the array)
Even though you're trying to treat something as a string which isn't a string, if all you want to do is print out the values in the struct, you can do something like:
struct data
{
int x;
int y;
};
int main()
{
data d;
d.x = 10;
d.y = 20;
cout << "x is " << d.x << ", y is " << d.y << endl;
}
Why are you trying to treat that struct as a string?