Home Assignment doesn't work but address of with the dereference operator does?

# Assignment doesn't work but address of with the dereference operator does?

user10751
1#
user10751 Published in September 21, 2018, 8:05 am

I've been playing around with C++ (just starting out), and I'm trying to make a program that needs a function to count the lines in C++. However, I've encountered weird behavior where normal assignment doesn't work, but assignment through address of, and then immediate dereference does. Like this:

int countLinesInFile(string fileName){
char c[32];
int numLines = 0;
ifstream file(fileName);

while(file >> c){
numLines += 1;
cout << "Lines: " << numLines << endl;
}
return numLines;
}


Which results in:

Lines: 1
Lines: 1
Lines: 1
Lines: 1
Lines: 1
Lines: 1


However, when I change numLines += 1 to *(&numLines) += 1 it magically works:

Lines: 1
Lines: 2
Lines: 3
Lines: 4
Lines: 5
Lines: 6


For a little background, the file I'm reading is a 6 line file where each line is a 32 bit binary string (equal to zero). When I print out c (with cout << c) it prints out seemingly correctly. Also, I am aware that this may not be the optimal or correct way of doing read lines from a file, but unless this simply can not possibly work, I am more interested in the underlying mechanics of why this behavior is happening, and what I am doing wrong.

## closed as off-topic by StoryTeller, Drew Dormann, Neil Butterworth, Captain Giraffe, 1201ProgramAlarm Feb 13 at 22:30

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting." – StoryTeller, Drew Dormann, Captain Giraffe, 1201ProgramAlarm
If this question can be reworded to fit the rules in the help center, please edit the question.

• Why are you using raw arrays with c++ (supposedly even c++11) code? – user9212993 Feb 13 at 21:55
• Could you explain why this is a problem, or a least give me a keyword to search for? – TimTheEnchanter Feb 13 at 21:57
• Ensure that ifstream file(fileName); was opened correctly. – user9212993 Feb 13 at 21:57
• 32 characters in each line of the file? Well, then you need a 33 character buffer. Otherwise, where is the nul terminating character gonna go? You have undefined behavior in your program. – StoryTeller Feb 13 at 21:58
• Ahhhh. The magic of undefined behaviour. Sometimes it is visibly wrong and sometimes it isn't. Sometimes it even looks right. – user4581301 Feb 13 at 22:36