Arrays and pointers

Why is this not working

void print_array(char *sour)
{
char * d = malloc(100 * sizeof(char));
while(*sour != '\0'){
    *d = *sour;
    s++,d++;
 }
printf("%s\n",d);
}

while this is working perfectly

void print_array(char *sour,char *dest) //dest is allocated in main.
{
while(*sour  != '\0'){
    *dest = *sour;
    sour++,dest++;
}

printf("%s\n",dest);
}

What do you mean by “not working”, can you be more specific?

Two observations:

  1. Where do d and dest point after the loop?
  2. In your first example you loose the address of the initially allocated memory block. After the loop there’s no way to free the memory so you have a leak.

Oh, and you need to increment sour in the first example, not s.

s was typo error. i get empty string.nothing at all.No result

Okay, yes, I’d expect that. After the loop the char pointers you’re trying to print point to one position after the string. You need to somehow save the start of the block. I’d strongly advise you not to do this kind of pointer arithmetic with dynamic memory anyway. You’re better off with something like this:

void print_array(const char* src) {
    char* dest = malloc(100 * sizeof(char));
    int i = 0;
    while (src[i] != '\0' && i < 100) {
        dest[i] = src[i];
        ++i;
    }
    printf("%s\n", dest);
    free(dest);
}

And you don’t even need to allocate anything here, you can keep dest on the stack then it’s automatically destroyed when the function exits.

void print_array(const char* src) {
    char dest[100] = { '\0' };
    int i = 0;
    while (src[i] != '\0' && i < 99) {
        dest[i] = src[i];
        ++i;
    }
    dest[i] = '\0';
    printf("%s\n", dest);
}

Last edit: And make sure you’re writing a null char at the end of dest so you don’t print random garbage.

yeah, i Got it.
I was just trying to write my own functions like strcmp,strcat but with pointers I got confused.
in strcpy they have used like

while((*sour ==  *dest) != '\0'){
      sour++,dest++;
}