
- Forum
- Programming Talk
- C and C++
- String Handling
String Handling
This is a discussion on String Handling within the C and C++ forums, part of the Programming Talk category; I have a doubt in string handling concept of C programming language. I wrote my C code as below: char ...
-
String Handling
I have a doubt in string handling concept of C programming language. I wrote my C code as below:
char *t1 = malloc(sizeof(char)*10);
char *t2 = malloc(sizeof(char)*10);
and then assign as
t2 = t1;
Will this copy the string t1 into t2. Can someone kindly give me brief idea on this?
-
06-06-2007, 03:23 AM #2
- Join Date
- May 2007
- Answers
- 12
char *t1 = malloc(sizeof(char)*10);
char *t2 = malloc(sizeof(char)*10);
writing above statements is not ANSI standard and is wrong to get desired result because malloc returns void* (pointer to void mean it returns pointer that points to nothing)
you have to parse the pointer returned by malloc as given below
char *t1 =(char*) malloc(sizeof(char)*10);
char *t2 = (char*)malloc(sizeof(char)*10);
sencondly, t1 and t2 do not hold values,
t1 and t2 hold memory address as allocated by malloc
so the statement t1=t2 does not assigns the values pointed by t2 but it assigns the address of the location pointed by t2
and after that statement t1 and t2 will hold same address or they will point to the same memory location. if you want to copy values
*t1 = *t2; is the statement.
-
06-06-2007, 06:42 AM #3
- Join Date
- Jun 2007
- Answers
- 1
Answer is
Yes it is possible there is no error you can copy two strings like this. In this you are sharing two pointer resources to t1 and t2.I have a doubt in string handling concept of C programming language. I wrote my C code as below:
char *t1 = malloc(sizeof(char)*10);
char *t2 = malloc(sizeof(char)*10);
and then assign as
t2 = t1;
Will this copy the string t1 into t2. Can someone kindly give me brief idea on this?
If any doubt mail to me laxman_balu at hotmail dot com
-
12-27-2010, 06:31 AM #4
- Join Date
- Dec 2010
- Answers
- 32
1stly...the above code is not correct and 2ndly t1 and t2 doesn't hold the data or value....its a pointer variable and molloc key word after creating the block sends the address of that block to the pointer variable.....so basically t1 as well as t2 holds the address of that block...
to fetch the data part you have to use Astrix operator before the name of the variable i.e. "*t2=*t1".....
this * means value to the address.......
-
Sponsored Ads

Reply With Quote






