poda_badu
poda_badu

Reputation: 161

pointer to pointer assignment in c

Why this code isn't working?

#include<stdio.h>
#include<stdlib.h>

int main(int argc,char **argv){

    char * new;
    new = malloc(10);
    const char * s1 = "hello";

    while(*s1){
        *new++ = *s1++;
    }
    printf("%s",new);

    return 0;
}

I ran the gdb and found that *s1 is not assigned to the *new. why?

Upvotes: 0

Views: 363

Answers (2)

babon
babon

Reputation: 3774

new is pointing to one byte past the last element of whatever was copied over from s1. You should pass the pointer to the first element of new to get the entire text.

Another problem is that you are not copying over the \0 from s1 to new. You should put a \0 at the end of new before trying to print it. Otherwise you are invoking UB.

You might do something like this and check:

#include<stdio.h>
#include<stdlib.h>

int main(int argc,char **argv){

    char * new, *new2;
    new = malloc(10);
    new2 = new;
    const char * s1 = "hello";
    while(*s1){
        printf("%c\n", *s1); // the \0 is *not* appended
        *new++ = *s1++;
    }
    *new = '\0';
    printf("%s\n",new2);
    return 0;
}

Upvotes: 5

H.S.
H.S.

Reputation: 12634

Because the new is pointing to the location one after the last character copied from s1 to new.

You can do:

#include<stdio.h>
#include<stdlib.h>

int main(int argc,char **argv){

    char *new, *tmp;
    new = malloc(10);
    if (new == NULL){
        printf ("Failed to allocate memory");
        return -1;
    }

    const char * s1 = "hello";
    tmp = new;   //take a temporary pointer and point it to new
    while(*s1){
       *tmp++ = *s1++;    //use tmp to copy data
    }
    *tmp = '\0';
    printf("%s",new);
    return 0; 
}

Upvotes: 1

Related Questions