Problem with const char* and strings

Sep 30, 2016 at 4:44am
I have a program that fails if I use a string but works if I use text.
I stripped it down to a simple failure:

here is app

#include <stdio.h>
#include <string.h>
#include <string>

const char* GATEWAY_ID;
const char* GatewayId ;

int main(int argc, char *argv[])
{
GATEWAY_ID = "T5YCD1";
printf("GATEWAY_ID = --%s--\n", GATEWAY_ID);
std::string arg1;
arg1 = "T5YCD1";
GatewayId = (char*)arg1.c_str();

// GatewayId = "T5YCD1"; \\ Uncomment and it fails?

printf("Gateway Id = --%s--\n", GatewayId);
printf("GATEWAY_ID = --%s--\n", GATEWAY_ID);

if (GatewayId == GATEWAY_ID) {
printf("They match 1\n");
}
else {
printf("They do not match 1\n");
int a = 0;
while ((unsigned)a <= strlen(GatewayId))
{
char byte1 = GatewayId[a];
char byte2 = GATEWAY_ID[a];
printf(" bytes is %d %d\n", byte1, byte2);
a++;
}
}
GATEWAY_ID = GatewayId;
printf("Gateway Id = --%s--\n", GatewayId);
printf("GATEWAY_ID = --%s--\n", GATEWAY_ID);
if (GatewayId == GATEWAY_ID) {
printf("They match 2\n");
}
else {
printf("They do not match 2\n");
}
}
Sep 30, 2016 at 9:03am
With == you are just comparing if the pointers point to the same location in memory. To compare C strings (char*) you should use std::strcmp. http://en.cppreference.com/w/cpp/string/byte/strcmp

Another, probably better, option is to simply use std::string everywhere. Then you can compare them using == without problem.
Oct 1, 2016 at 2:13am
This is an excerpt from a larger program an the calling functions require const char*.
When you run the app with an input argument of T5YCD1
They will display the same, the byte by byte will be the same.
The second if statement says they match.

I tried changing the if statement to
if(*GatewayId == *GATEWAY_ID)

and it report they match, even when they don't. I changed
GATEWAY_ID = "T5YCD1"; to
GATEWAY_ID = "T5YCD2";
just to test.
An kept the same input of T5YCD1.

I am new to c++.
Do i need to do the assignment of string to const char* a different way.

Oct 1, 2016 at 2:21am
I tried changing the if statement to
if(*GatewayId == *GATEWAY_ID)



Dereferencing a pointer-to-char, gives you a char. You can't compare a string to another by comparing a single character of one to a single character of the other. Perhaps you should avail yourself of the suggestion to use std::strcmp.
Topic archived. No new replies allowed.