user12591754
user12591754

Reputation:

copy char array to char* in C

I have a char array that I need to define in a function and return a char pointer, so i defined MAX which is the biggest size my char array can be according to my assigment and after I append part of it I want to copy it to char pointer so I can return it. the size of the part of the array that is full is i and I did malloc to with this size, then I did memcpy to copy only the part I want(strcpy copied also the ampty fields), but it still put in my result more weird stuff, how do I get rid of this?

Code:

char* result = (char*)malloc(i*sizeof(char));

if (result == NULL)
    free(result);

memcpy(result, temp, i);

printf("%s", result);
return result;

Result of printf:

ccbcc²²²²U┤

while the result should be only "ccbcc".

Upvotes: 0

Views: 368

Answers (1)

Himanshu Singh
Himanshu Singh

Reputation: 2165

Instead of printing like this: printf("%s", result);

you should be printing only indexes which are initialized and contains value:

for(int k=0;k<i;k++){
  printf("%c", s[k]);
}

Upvotes: 1

Related Questions