This question already has answers here:
What is a reference variable in C++?
(12 answers)
Closed 7 years ago.
The function get of an ifstream reads the next character and stores it in the argument you pass to the function. Example program:
#include <iostream>
#include <fstream>
int main () {
std::ifstream is("input.txt"); // open file
char c;
while (is.get(c)) // loop getting single characters
std::cout << c;
is.close(); // close file
return 0;
}
This works great but I am puzzled by how c can be changed by the function get as it is not passed by its pointer. I was told, some time ago, that modifying a variable within a function cannot change its value outside the function. And that's the whole purpose of pointers, right -- manipulating an object created outside the function. So how can c be changed here?
I guess there is something obvious that I don't understand here?
The member function std::istream::get() uses a reference:
istream& get (char& c);
This means that the function accesses directly to the variable passed as a parameter.
If you're not familiar with references, here you can learn more.
"So how can c be changed here?"
As from the reference documentation std::ifstream::get() uses a parameter passed by reference for the char variable
basic_istream& get( char_type& ch );
so it alters it by using this reference.
Related
This question already has answers here:
Returning an array using C
(8 answers)
Closed 6 months ago.
I wrote a simple c++ program where i am getting a simple float Array from a function. Then I call a function where the generated Array is a parameter of. I print the first value of the Array through the function. It works! BUT when i am declaring another array in the function before i print the value from the first array, the printed value is not the expected one. MAGIC!
CODE THAT DOESN'T WORK:
#include <iostream>;
float* getArray() {
float Array[] = { 4 };
return Array;
}
void compute(float* Array) {
bool newArray[1];
float content = Array[0]; //breakpoint: content will be -107374176.
std::cout << content;
}
int main() {
float* Array = getArray();
compute(Array);
}
OUTPUT: -1.07374e+08
When removing the line "bool newArray[1];" (line 10) the code starts to work.
OUTPUT: 4
Test it your self! Can someone explain me why this happens?
Your main function has a bug. It passes a pointer to Array to compute, which dereferences it. But Array is out of scope at this point since its scope ends when getArray ends. So you are trying to access an object that no longer exists. That is undefined behavior and produces completely unpredictable results.
Arguably, getArray also has a bug since it always returns a pointer to an object that no longer exists. So there is no way to use it. Whether or not that's a bug depends on what the caller is supposed to be able to do with the returned value which cannot be determined due to the lack of comments.
This question already has answers here:
what is the meaning of (*(int (*)())a)()?
(3 answers)
Closed 4 years ago.
I was reading this answer: https://stackoverflow.com/a/5539302/588867
What is going on with this part: (int (*)(int))tolower in this line of code:
transform(s.begin(),s.end(),s.begin(),(int (*)(int))tolower );
If I make this function and the code works:
int myToLower(int c){
return tolower(c);
}
transform(s.begin(),s.end(),s.begin(), myToLower);
What's plain English about this part: (int (*)(int)).
You can see this answered in my answer, that's a function pointer. You can read more about them here: http://en.cppreference.com/w/cpp/language/pointer#Pointers_to_functions
Fundamentally this is a pointer to a function that takes in an int argument and returns an int.
The reason the transform works when using myToLower and not with an uncast tolower, is that in code is that the tolower function is overloaded in the std namespace by both the locale library's tolower and the ctype library's tolower. When only the function name is used as an uncast pointer no overload resolution is performed, and you'll get an error. When you cast the function pointer you're telling the compiler which overload you want.
This question already has answers here:
returning a local variable from function in C [duplicate]
(4 answers)
Closed 8 years ago.
I guess its a storage/definition difference but still I cant find a straight explanation of the behaviour. I have a function that returns a locally defined char* in two ways:
//Try 1:
char* printSomething()
{
char arr[100];
sprintf(arr, "The data %u", 100);
return arr;
}
//Try 2:
char* printSomething()
{
return "The data 100";
}
When I print the result of the first function It displays nothing (C) or garbage (C++) while on the second it prints the correct data.
I know I should store the data on the heap in cases like this or define static variable but still, how come the first doesnt work while the second does? and also, can I count on the second way to always work?
The first is just undefined behavior because arr is released when the function ends, so you're left with a dangling pointer.
The second works because "The data 100" is a string literal with static storage duration, which means it persists throught the lifetime of the program.
The implicit conversion to char* is deprecated though, and changing the contents will result in undefined behavior. I suggest you return const char* or std::string.
In both cases you returning char*
The first you return a pointer to a local array variable, located on the stack, which no longer exists after you exit the function. and may be rewritten.
In the second you returning pointer to a const string, located on the code segment, and it exist as long as the program is running.
This question already has answers here:
c++ change function's variable argument
(2 answers)
Closed 8 years ago.
Say I have
string stringInput = "hello";
alter(stringInput);
cout << stringInput;
and a function:
void alter(string stringIn){
stringIn[0] = stringIn[3];
}
Ideally I would want cout to produce "lello". But right now it simply returns "hello" as originally. I know this has something to do with addresses and pointers... how would I achieve this?
It's actually just because a new copy of the string is created for use in the function. To modify the string directly in the function add an & before the string name in the function header like this:
void alter(string &stringIn){
That passes the string by reference. Otherwise you could just return a string from the function.
All you need to do is to pass the string by reference:
void alter(string& stringIn){
// ^
stringIn[0] = stringIn[3];
}
You should also modify accordingly any function declarations you have for alter().
Your stringIn is a local variable. So when you pass it on the function as a value it just makes a new stringIn with different address. So the changes you are making in alter is only affecting the new stringIn. You need to recieve the reference of the stringIn in alter to make it work.
void alter(string& stringIn){
stringIn[0] = stringIn[3];
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is address of char data not displayed?
I was experimenting with ampersand operator and got stuck at this program :
#include<iostream>
using namespace std;
int main() {
char i='a';
cout<<&i;
return 1;
}
I was expecting the address of variable i as the output but instead the output came as the value of variable i itself.
Can anybody explain what just happened? Thanx in advance.
That's because cout::operator<< has an overload for const char*. You'll need an explicit cast to print the address:
cout<<static_cast<void*>(&i);
This will call the overload with void* as parameter, which is the one used to print addresses.
Also note that your code runs into undefined behavior. You only have a single char there, and the overload expects a null-terminated C-string.