Substract strings - int result [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Can anyone explain why do I get the result 4 after using
a[]="informatics";
cout<<strchr(a, 't')-(a+3);
Shouldn't I get the result of -4?
Because I subtract a shorter string ("tics") from "ormatics". In my opinion, if I had "ormatics-tics" it would make sense to return a string, orma, not a number at all.
Why is that, I can't find reference of this thing. Also, when I tried the same thing, after I done myself what strchr returns, I got -4:
cout<<" tics"-"ormatics";`
Can someone explain please?

a holds the pointer to the first character of the char array containing "informatics".
strchr(a, 't') returns the pointer to the first "t" (which is the 8th character).
the result is a+7.
so your calculation resolves to:
strchr(a, 't')-(a+3) == (a+7)-(a+3) == 7-3 == 4
Edit:
This answer is a bit misleading as it implies that a is a pointer.
This is wrong! a is an array and not a pointer.
The differences are best explained here: c-faq - Arrays and Pointers
A better wording would be that an array often is used like a pointer, as some operations simply use the address of the first element of the array.
A improved calculation could look like this:
strchr(a, 't')-(a+3) == (&a[0] +7)-(&a[0] +3) == 7-3 == 4
(Thank you Martin Bonner for pointing that out.)

You are doing a Pointer subtraction.
This is what is happening :
So strchr(a, 't')-(a+3) is,
(0+7)-(0+3) => 4
*Considering a to be 0 for simplicity *
Note : When you subtract two pointers, as long as they point into the
same array, the result is the number of elements separating them
Source

" tics"-"ormatics"
substracts two arbitrary const char* pointers. There can't be any prediction made about the difference.
There's absolutely no relation to their actual string contents.

Let me extend your example:
const char a[]="informatics"; // a is an array with 12 elements (inc terminator).
const char* const pa = a; // pa is a pointer to char. Let us say for the sake of
// argument it has value 0x1000
const auto pt = strchr(a,'t') // pt will be a pointer with value 0x1007
const auto ap3 = a+3 // ap3 will be a pointer with value 0x1003
const auto diff = pt - ap3; // diff will be type ptrdiff_t, and given the values
// above, you shouldn't be surprised it has
// value 4.
std::cout<<diff<<std::endl; // Will output "4".

Related

coping an array from one object to another object [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
set &set::operator=(set const &s) {
elems = new int[s.num_elems];
num_elems = *(new size_t);
for (size_t i = 0; i < s.num_elems; i++) {//i am getting error in this line on "=" saying " a value type int* cannot be assigned tpo an entity of type int".
elems[i] = &(s.elems[i]);
}
num_elems = s.num_elems;
return *this;
};
i am trying to copy an object to another object they each has two private size_t num_elems and int *elems.i have tried changing the pointer symbols and copying the array directly but it gives me error everytime
This line is bad: num_elems = *(new size_t);
It just leaks a few bytes and does nothing useful. Delete it.
Then there is a problem where you are assigning the address of s.elems[i] into elems[i]. Which is not right because elems[i] is an integer, and the address of s.elems[i] is... well, an address.
So you need to change this line: elems[i] = &(s.elems[i]); to this: elems[i] = s.elems[i];
A few tips:
& this is called the "address of" operator. It gets the address of where something is in memory.
* this is called the "pointer dereference" operator. It helps you access what the pointer is pointing at.
When you access an array with square brackets, like this: elems[i] you're de-referencing it. Which means you're using the value that the pointer is pointing at. It's the same as doing this: *(elems + i)
Study your pointers :D They're a little tricky at first but they get easier with time and practice.

wrong printing 2D char array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am doing my homework and I declared a 2D array but it's not printing what I want.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char NOTE[7][3] = { {'D','O'} , {'R','E'} , {'M','I'} , {'F','A'} , {'S','O','L'} , {'L','A'} , {'S','I'} };
for (int i = 0; i <7 ; i++)
cout <<setw(10)<< NOTE[i] << "\n";
return 0;
}
I want to get:
DO
RE
MI
FA
SOL
LA
SI
DO
but I got:
DO
RE
MI
FA
SOLLA
LA
SI
DO
NOTE[i] is an array of characters. << NOTE[i] inserts this array into a character stream. The array argument decays to a pointer to the first character.
The documentation says that behaviour is undefined unless the pointer operand points to a null terminated array. The array {'S','O','L'} is not null terminated. Therefore the behaviour of the program is undefined - although it could be argued that the behaviour of iterating across boundaries subarrays of a multidimensional array should be well defined (with the behaviour shown in your program), but strict interpretation of the standard is that doing so is UB.
So, to get the output you want, you either need to 1. null terminate each sub array (and therefore need a larger array), or to 2. print each character individually.

How to dereference an array element (C++) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I wanted to create an array of a specific size using a variable, but allegedly the only way to do that is to use pointers.
int size = 5;
string* myArray = new string[size];
I now want to assign an element from this array to another variable, which I believe will only work through dereferencing. The following line of code doesn't work. How do I fix it?
string line;
myArray[0] = "Hello";
line = *myArray[0];
Edit:
I just want to clarify something: Using the normal "myArray[0]" code doesn't work either. It compiles, but causes a crash. Here's some more specific code regarding what I want to do.
void MyClass::setLine(string line)
{
myLine = line; /*This is a private variable in MyClass*/
}
///////////////
MyClass* elements = new MyClass[size];
elements[0].setLine(myArray[0]);
I want to assign the array element to a private variable from a class, but the program crashes when I try to assign the value to the private variable.
If you know the size at compile time, you can use a normal array. If you only know the size at runtime, you could still use a std::vector, which is far easier to use than manual allocation.
Anyway, if you really want to learn about pointers for array managing, keep in mind that the index operator is equivalent to addition and dereference, i.e. ar[i] is the same as *(ar + i). In other words, indexing is just dereferencing at an offset.
As such, no extra dereference is needed. Just drop the asterisk in the failing line.
Valid code will look like
string line;
myArray[0] = "Hello";
line = myArray[0];
By the way you could use class std::vector instead of the array if you are going to add or remove elements from the collection.
For example
std::vector<std::string> myArray;
myArrray.reserve( 5 );
myArray.push_back( "Hello" );
line = myArray[0];

How do I typecast a void * pointer in C++? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have the following code:
#include <iostream>
using namespace std;
int main() {
// your code goes here
float _t100;
void * _t200;
float _t300;
_t100 = -5.0;
_t200 = &_t100;
_t300 = *(float *)&_t200;
cout<<_t300;
return 0;
}
It prints -1.61669. Why? It should print -5.0.
It's because &_t200 is the address of _t200. Since _t200 is a void*, its address is a void **.
I think you meant to do
_t300 = *(float*)_t200;
By the way, symbols beginning with _ are reserved; you should not name variables this way.
You have an extra & in your code: this line
_t300 = *(float *)&_t200;
does not need an ampersand, because _t200 is already a pointer:
_t300 = *(float *)_t200;
demo.
Your error is here:
_t300 = *(float *)&_t200;
You are taking the address of _t200, making it a void**, so when you print it you're actually printing the address of t_200
In your code you're not casting a void* - you're casting &_t200, which is a void**. If you leave out the &, you get the result you want.
This expresison
*(float *) &_t200;
reinterprets the memory occupied by the pointer _t200 as a float object and evaluates to that float value. I.e. -1.61669 that you see is the content of the pointer _t200 itself (i.e. an address) reinterpreted as float.
This is probably not what you wanted to do.
If you want to get access to your original -5.0 value stored in _t100, you have to reinterpret the memory _t200 is pointing to, not the memory _t200 occupies itself. The following expression
*(float *) _t200;
would do exactly that.

Passing a LPDWORD as out parameter [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am new to C++ and I need to create a function with this structure:
BOOL myfunc(LPDWORD myLpdword){ // myLpdword must be an out parameter
DWORD myDword = 1;
myLpdword = &myDword;
return true;
}
int main(){
DWORD outDword = 20;
myfunc(&outDword);
cout << outDword << end1;
return 0;
}
I expected that the value of outDword would be 1 (changed by myfunc), but the value is not changed by myfunc.
Please, can you give me a hint to solve this problem?
Like this
BOOL myfunc(LPDWORD myLpdword){ // myLpdword must be an out parameter
*myLpdword = 1;
return true;
}
Out parameter is not something that means anything in C++. MS use it but only because they are using a consistent terminology across different languages.
In C++ terms what you did is pass a pointer to the variable you want to modify to myfunc. What the above code does is take that pointer and dereference with the * operator it to modify the variable you wanted modified.
I like that you're writing small test programs to check your understanding of C++. But as others said there's no real substitute for a decent book. Any C++ book is going to cover this.
You passed in a pointer to outDword.
myLpdword is now a pointer to outDword.
You then changed myLpdword to be a pointer to myDword.
You never did anything with the VALUE of outDword.
You assigned the pointer of a variable that will not exist after exiting the function body (read on scopes in C/C++.
To solve your problem, assign the value of the variable to the dereferenced pointer, like so: *myLpdword = myDword;. It would also be wise to check that the value of the pointer is not null before dereferencing it like this: if (myLpdword == 0) { return; } . This check doesn't guarantee that the pointer is safe to assign to, but Atleast guards you against null pointer access.
In C++ this is called pass-by-reference. You denote it with an ampersand in the function signature:
bool myfunc(DWORD &myDword) {…
The ampersands you are using now are actually getting the address of the variables, so you should remove those.