char * abc = (char *)

Mar 13, 2013 at 7:50am
char * abc = (char *)"1ns"


what does this code do? which chapter of C or C++ can find this ?
Mar 13, 2013 at 8:41am
Does unnessesary and dangerous c-style cast.
you can simply write: char * abc = "1ns";
But any attempt to change abc sting value like abc[1] = 'T'; will lead to segfault.
Best variant: const char * abc = "1ns";: it is safe and syntaxically correct.

(char*)something is a c-style cast. In C++ you should use static_cast<char*>(something)
Last edited on Mar 13, 2013 at 8:43am
Mar 13, 2013 at 8:50am
Okay.Thanks MiiNiPaa.
So what way is the best way to write the source code without leading to segfault as well.
Mar 13, 2013 at 9:02am
const char * abc = "1ns";
You can use it as string constant but won be able to change it.

You can write const char abc[] = "1ns";
And it will be equivalent to:
1
2
char abc[4];
strcpy (str3,"1ns")

That way you can change your string.

Or you can use string class provided in <string> library.
Mar 13, 2013 at 9:05am
Got it. Thanks very much!
Mar 13, 2013 at 9:15am
hey MiniPaa, I had the following queries:

1. when we write
const char * abc = "1ns";
are we declaring the pointer abc as constant or the present value pointed by it as a constant.

2. How are we able to change the value of abc by declaring it the following way?
const char abc[] = "1ns";
aren't we declaring abc as a constant?
Mar 13, 2013 at 9:18am
@MiiNiPaa: strcpy is considered dangerous. Don't use it to copy c-strings...

for example
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
  char str[10];  //maximum of 9 chars 

  strcpy(str,"0123456789abcdef");  //"fine", but str is allowed maximum of 9 characters only!

  cout << str << endl;  //print 0123456789abcdef, 16 chars !!
}


Use strncpy instead
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
  char str[10];

  strncpy(str,"0123456789abcdef",9);  //copy maximum of 9 chars in "0123456789abcdef"

  cout << str << endl;  //print 012345678, great!
}

Mar 13, 2013 at 9:20am
Non-Constant Pointer to Constant Data: The address of the pointer can be change. The data pointed to by the pointer cannot be changed.
1
2
3
4
int x = 5, y = 6;
const int * iPtr = &x;
*iPtr = 6;   // Error: the value pointed to cannot be changed
iPtr = &y;   // You can change the address of the pointer 
Last edited on Mar 13, 2013 at 9:24am
Mar 13, 2013 at 9:24am
strcopy() works fine when you are using it for initial variable ititialization. Beacause you know in advance both array and literal constant size. My code with it was just an example of what that code equivalent to.

@abhishekm71:
1) We are declaring data variable points to as const. You still can change where pointer is point to.

2) Sorry, my bad. Drop the const: char abc[] = "1ns";
Last edited on Mar 13, 2013 at 9:25am
Mar 13, 2013 at 9:45am
ok.. thanks MiniPaa!
Topic archived. No new replies allowed.