简体   繁体   中英

pointers in c++ debugging

I am currently trying to learn C++ from a book that I got from a friend of mine a couple of days ago. I I've seen some codes as a quiz in the book that I need to solve. So I tried to solve them but I'm not sure if my assumption is right.

This is the first one

char* r(char *g){ // can someone explain this line for me? I'm not sure what is it saying
char ch = 'B'; // is the code going to be correct if I changed char ch to char* ch? 
return &ch; // since this is &ch, then the previous line should be char* ch, am I right?
  }

The second code:

    char* a;
    a = new char[strlen(b)]; // will this line cause a compiling error just because b is undefined ? since there is no length for b because it's not even there?
    strcpy(a,b); // since we're using strcpy() a and b has to be pointers am I right?

I am not asking for the answers, I need someone to tell me whether am right or wrong and why please.

char* r(char *g){ // can someone explain this line for me? I'm not sure what is it saying

Declares a function, r which takes one argument, a pointer g to contain the address of one or more characters.

char ch = 'B';

Declares a variable, ch of type char and assigns it a value 'B'. That is - it will contain a number which is the position in the ASCII chart of the letter B. It's going to contain the number 66, but when you print it out, it will produce the letter 'B'. (see http://www.asciitable.com/ )

This variable will likely be on the stack. It could be in a register, but compilers are generally smart and the next line will ensure it is on the stack.

return &ch;

In this context, & is the address of operator.

return address_of(ch);

Since ch is of type char , &ch produces a value which is of type char* .

char* a;

Declares a variable a with no initial value. This is a bad thing to get into the habbit of writing.

a = new char[strlen(b)];

You say that b doesn't exist, but I think it's assumed to be of type char* - a pointer to one or more characters. In C and C++ a "C-String" is an array of 'char' values (characters) terminated by a char of value 0 (not the character '0', which has an ASCII value of 48, but 0, or '\\0'). This is called a 'terminating nul' or a 'nul character' or a 'nul byte'.

The string "hello" is actually representable as an array { 'h', 'e', 'l', 'l', 'o', 0 } . Contrast with "hell0" , which would be { 'h', 'e', 'l', 'l', '0', 0 };

The function strlen counts the number of characters from the address it is called with until it finds a nul. If b was the address of "hello", strlen would return 5.

new allocates memory for an object, or in this case an array of objects of type char, the number of which is the return value of strlen.

size_t len = strlen(b);
char* a = new char[len];

At this point in the code, recall my explanation about terminating nul and that strlen returns the number of characters before it finds the 0. To store a C-string you need the number of characters PLUS space for a terminating NULL.

If b is the string "A", it consists one character ('A') but two *char*s - 'A', and 0. Strlen returns the number of characters.

strcpy(a, b);

This will copy the characters pointed to by b to the address at a , *including the terminating nul.

The bug here is that you only allocated enough memory for the characters.

char* a = new char[strlen(b) + 1];
strcpy(a, b);

Again - strlen is always going to return the length - the number of characters, and you're always going to want one more than that, for the nul.

would be correct - otherwise you're going to overwrite the memory allocated to you and cause a corruption.

--- EDIT ---

Throwing some of this together, live demo here: http://ideone.com/X8HPxP

#include #include

int main() { char a[] = "hello"; std::cout << "a starts out as [" << a << "]\\n";

   // C/C++ arrays are 0-based, that is:
   a[0] = 'H'; // changes a to "Hello"

   std::cout << "a is now [" << a << "]\n";

   std::cout << "strlen(a) returns " << strlen(a) << "\n";

   // But that is based on counting characters until the 0.
   a[3] = 0; // one way to write it,
   a[3] = '\0'; // some people prefer writing it this way.

   std::cout << "a changed to [" << a << "]\n";

   std::cout << "strlen(a) is now " << strlen(a) << "\n";

   return 0;

}

First Code:

r is function name having return type char* ie reference type and accepting parameter of reference type char* g.

'B' is assigned to ch variable.

r function returns the address of ch variable.

According to me no correction required in First code.

Second Code:

Yes it will cause compilation error at line 2 as b is not declared or defined.

char* r(char *g){ 

here r() is function which take char* as argument and return char*

char ch = 'B'; 
return &ch;

Here, ch is char locally defined and you are returning it. This is not good. Better use char*. Also char will have only one character whereas if you use char* you can have more than one.

char* ch = "Thats My string";
return ch; //Notice ch is a pointer. No need to use &

Second Code:

char* a;
a = new char[strlen(b)];

If b is undefined, sure there will be error. If b is char* with some value assigned to it strlen will provide you length of string which b is having. so this looks good.

strcpy(a,b); // since we're using strcpy() a and b has to be pointers am I right?

Yes you are right! You can use strncpy instead.

1st Code:

You are defining a function called r which accepts a pointer to a char and returns a pointer to a char.

char* r(char *g){ 
    //stack char variable ch is initialized to B
    //changing char ch to char *ch will compile (with a warning) but then the address pointed by ch will contain garbage (value of 'B' projected as an address).
    char ch = 'B';
    //you are returning the address of ch which as seen above is a stack variable so you are causing undefined behavior. You should avoid this.
    return &ch; 
}

2nd Code:

char* a;
// if b is undefined as you state then following line will cause compiling error. strlen() will calculate the length of the area at runtime so b must be at lease defined first.
a = new char[strlen(b)];  
//a is a pointer as you defined it above and points to the heap memory allocated by new
strcpy(a,b); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM