Exforsys
+ Reply to Thread
Results 1 to 4 of 4

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 ...

  1. #1
    Ralph is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    114

    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?


  2. #2
    Mukhtar Ahmad is offline Junior Member Array
    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.


  3. #3
    laxman Dodda is offline Junior Member Array
    Join Date
    Jun 2007
    Answers
    1

    Answer is

    Quote Originally Posted by Ralph View Post
    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?
    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.
    If any doubt mail to me laxman_balu at hotmail dot com


  4. #4
    Manyamanas is offline Member Array
    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



Latest Article

Network Security Risk Assessment and Measurement

Read More...