It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
#include <iostream>
using namespace std;
int main()
{
char *fp = "Alex";
cout<<fp <<" "<<(void*)fp<<endl;
*(fp+1) = 'p';
cout<<fp <<" "<<(void*)fp<<endl;
}
You modified a string literal. That's undefined behavior.
Increase the warning level on your compiler, you want a warning/error for the line char *fp = "Alex";, because it creates a non-const pointer to immutable data. It's only allowed in C++ for compatibility with C, and it's a misfeature there too.
I don't really like answering "questions" like this, but here is an obvious error:
*(fp+1) = 'p';
fp points to readonly memory as you assigned a string literal to it. Thus, you cannot modify what fp points to. If you want to modify the string declare fp as a char[] so that it will be allocated on the stack.
I'm going to have to assume that you are talking about the following compiler warning:
prog.cpp: In function ‘int main()’:
prog.cpp:5: warning: deprecated conversion from string constant to ‘char*’
Next time please tell us in the question why it is that you think something is "wrong".
As the warning states, converting string constants to char*, whilst fairly normal in C, is deprecated in C++.
Do this instead:
#include <iostream>
using namespace std;
int main() {
char const *fp = "Alex"; // <--- `const` here
cout<<fp <<" "<<(void*)fp<<endl;
*(fp+1) = 'p';
cout<<fp <<" "<<(void*)fp<<endl;
}
You will then find that your statement *(fp+1) = 'p' does not compile. That is because of the const; in fact, the lack of const in your original code merely hid the fact that you may not modify the underlying data of that string literal.
You should copy the characters to a new buffer that your program owns. You can do this neatly using std::string:
#include <iostream>
#include <string>
using namespace std;
int main() {
string fp = "Alex";
cout << fp << " ";
fp[1] = 'p';
cout << fp << " ";
}
In general, use std::string wherever you can. There is rarely a reason to avoid the features of the C++ Standard Library.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I think the title makes it self explanatory. The actual code is quite long but here's and example that I think matches the problem.
#include <iostream>
using namespace std;
char multiDArray [5][5];
multiDarray[1][2] = 'x';
char barrier = 'x';
int main () {
if (multiDArray[1][2] == barrier) {
cout << "It works". }
}
This doesn't give me an error, but nothing happens when I run the program.
Thanks for your help.
I have modified the code you provided so that it compiles:
#include <iostream>
using namespace std;
char multiDArray [5][5];
char barrier = 'x';
int main ()
{
multiDArray[1][2] = 'x';
if (multiDArray[1][2] == barrier) {
cout << "It works";
}
return 0;
}
You'll see here (http://ideone.com/MFn9yM) that it does indeed work.
Output:
It works
It's possible you are seeing no output in your larger program because you are not flushing the output buffer (using std::flush or by including a newline).
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I feel so lost trying to figure this out. I have my own data structure that I am planning on using vectors to avoid having to keep track of free space and reorginization that I would need to do if I used a simple array. I don't don't know if I'm just not initializing properly or what, but every assignment I do seems to just disappear into thin air.
Here is some simple code to illustrate what I'm talking about:
#include <vector>
#include <iostream>
using namespace std;
struct node
{
int test_int;
bool test_bool;
};
struct file
{
vector<node> test_file;
};
int main()
{
file myfile;
int myint;
cout << "Enter number: ";
cin >> myint;
myfile.test_file[0].test_int = myint;
cout << "Number entered is: " << myfile.test_file[0].test_int << endl;
return 0;
}
So basically it is a vector inside a struct. It seems that the normal ways to access a vector don't seem to work, as in I can't read or write anything to the vector however things like myfile.test_file.size() seem to work (as in they return a '0' from a freshly created struct). Trying to access the index directly by myfile.test_file[0].test_int results in a runtime error of vector subscript out of range as if it isn't actually there.
Am I not initializing it properly? This seems kind of ridiculous to me and I can't understand why it wouldn't work that way.
Edit:
Edited code to more clearly show behavior I'm referring to. This compiles but gives a runtime error vector subscript out of range
The edited version doesn't work because you're accessing an element past the end of the vector:
myfile.test_file[0].test_int = myint;
Before you can do this, you need to either resize() the vector, or add an element using push_back():
myfile.test_file.push_back(node());
myfile.test_file[0].test_int = myint;
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
char* a = "aaa";
map<char*, int> m;
m.insert(pair<char*, int>(a,5));
a[0] = 'c';
a[1] = 'c';
a[2] = 'c';
cout << a << endl; // a = `ccc`
cout << m["aaa"] << endl; // found the node by `aaa`,
cout << m.begin()->first << endl; // but the node's left is actually `ccc`?
So the node's left is ccc or aaa?
Actually it does not found the node by "aaa" nor "ccc", it founds the node by the memory address a points to. Comparison between pointers does just that, it does not perform a string comparison. If you want to index by a string, then use an std::string.
I didn't understand the question properly. Still, there are few things in your code I would like to comment on, such as:
char* a = "aaa";
This is deprecated. Didn't your compiler give warning message? It should be written as:
const char* a = "aaa";
a[0] = 'c'; //it should be an error if you correctly declare `a`
a[1] = 'c'; //it should be an error if you correctly declare `a`
a[2] = 'c'; //it should be an error if you correctly declare `a`
It's precisely because you shouldn't do this, the declaraton of a in your code is deprecated. If you declare a as I suggested (which is correct also), then the compiler would give error for the above assignment statements.
Moreover, if a is const char*, then your question "the node's left is ccc or aaa?" wouldn't arise in the first place. Because a is after all points to const data, and so you cannot change it, thus m.begin()->first will always be aaa.
Also, the map declaration should be:
map<const char*, int> m;
Or even better would be this:
map<std::string, int> m;
The type of the string literal "aaa" is const char[4]. Despite the type of a being char* (pointer to modifiable char), you've made it point to a read-only memory location.
The line a[0] = 'c'; invokes undefined behavior and, on most compilers, a runtime failure.
Your compiler, apparently, permitted your program to modify the value of the literal "aaa" in this manner, so that the values "ccc" were stored at its memory location. However, when you asked the compiler to generate a pointer to "aaa" again later on, it produced the same address of what it thought was the string "aaa" in its static data section,
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
This is probably a basic question.
I have a vector of a data type 'player' that I have defined myself using a struct:
struct player {
string player_name;
string label;
...
...
}
I then having a function taking a vector of these player data types as a parameter and I want to access the members in the struct i.e.
void foo(vector<player> players) {
cout << players.at(0).player_name;
}
The at(i) works because it is a function of vector. However, I can't access player_name. Why is this and how can I solve it? Apologies if this is basic and boring.
Following code accesses player in vector:
#include <string>
#include <vector>
using namespace std;
struct player {
string player_name;
string label;
};
int main() {
vector <player> p;
p.push_back( player() );
p.at(0).player_name = "fred";
}
Your problem is that foo() returns but you don't see the side-effect of the changed player_name, I guess?
It's because you've passed the vector to foo() by value rather than reference. foo() is operating on a copy of the vector rather than whatever original you passed to it, so the player_name change is lost when the function ends.
Try changing the function signature to void foo(vector<player>& players).
(Note that I've added an ampersand to make the parameter a reference.)
You should not get a compilation error since the code you posted is fine. If you are getting a runtime-error make sure you have inserted at least one object into the vector before you try to access it.
just speculation
if you get a compile error:
probably you declare a class instead of a struct.
if you get a runtime error:
the vector is empty
no error but not result:
you haven't flush the stream. Add std::endl or call std::cout.flush()
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I have problem with char in my code, please guide me (c++).
I have this error: Run-Time Check Failure #3 - The variable 'op' is being used without being initialized. What does it mean and how do I fix it?
This is my code:
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
using namespace std;
enum Operations {SIN1, COS1, TAN1};
void selectenteroperation(char *szInput) {
char *szLabels[3] = {"sin", "cos", "tan"};
int i=0;
while(strcmp(szInput,szLabels[i])==0)
++i;
switch (i)
{
case SIN1: { cout<<"SIN"; break; }
case COS1: { cout<<"COS"; break; }
case TAN1: { cout<<"TAN"; break; }
default: { cout<<"Wrong"; break; }
}
}
void main() {
char *op;
cout<<"op?";
cin>>op;
if(strcmp(op,"sin")==0) selectenteroperation("sin");
if(strcmp(op,"cos")==0) selectenteroperation("cos");
if(strcmp(op,"tan")==0) selectenteroperation("tan");
}
It's because char *op creates just a character pointer, not the backing storage to hold the string.
Since this is C++, you should be using std::string. Old style C strings have their uses but easy-to-use strings is not one of them.
Embrace C++, there are more than enough C programmers trying to pass themselves off as C++ gurus as it is :-)
Since this looks like homework, I won't give you back your fully fixed program but I will give you one that can be used as a basis for testing and, more importantly, understanding:
pax$ cat qq.cpp ; g++ -o qq qq.cpp
#include <iostream>
int main (void) {
std::string s;
std::cout << "Enter something: ";
std::cin >> s; // or getline (std::cin, s).
std::cout << "You entered [" << s << "]" << std::endl;
return 0;
}
pax$ ./qq
Enter something: hello
You entered [hello]
Alternatively, if you really want to use C strings, something like:
#include <iostream>
int main (void) {
char s[256];
std::cout << "Enter something: ";
std::cin.getline (s, sizeof (s));
std::cout << "You entered [" << s << "]" << std::endl;
return 0;
}
may be suitable.
I think you should check out the standard template library string class instead of using a C-string (char*) for your op variable.
I'm guessing you probably want to change the line:
while(strcmp(szInput,szLabels[i])==0)
to
while(strcmp(szInput,szLabels[i])!=0)
edit:But you should also have a test here to make sure i doesn't exceed 2.
And of course you also need to allocate memory for *op, like this:
char *op = new char[256] ;
(I just chose 256 arbitrarily here).
UPDATE: To test that i is less than 3:
while(i<3 && strcmp(szInput,szLabels[i])!=0)
You are reading into a uninitalized char* pointer. A quick (if somewhat dangerous fix) would be to write:
char op[100];
instead of
char* op;
but using std::strings is much safer as others have pointed out.
The answer is that you don't have a char -- you have a pointer to a char. The pointer is uninitialised.
char *op;
cout<<"op?";
cin>>op;
Do something like
char *op = new char[100];
Or use std::string instead.
char *op;
cout>op;
The above code is wrong. Trying to write to some memory that has not been initialized !!
Try using a char array or a string instead of a raw char pointer
Your code has many problems:
strcmp returns 0 when the strings are EQUAL, not when they're different
you should think a way to stop searching once you get to the end of szLabels
string literals cannot be altered and so it's better to use const char * in that case
main should not declared that way (it's not a void function)
cin >> op is not going to allocate the needed memory for your input
C++ has a std::string class that can solve many of the above issues and seems to be just the right thing to use here
I hope you're not going to feel offended, but to me looks like you're using C++ as the first language to learning about programming. I personally think this is a recipe for a disaster.
If for some strange reason you really must use this difficult path then my suggestion is to start from a good introductory book and following examples first.
C++ isn't a good language for just "try and see". IMO typing in code and trying to compile is bad in general, but is a true suicide with a language powerful but complex and asymmetric as it is C++ especially if you consider that when you make a mistake often C++ will just laugh at you instead of clearing telling you where is the mistake.