Assigning a char value to char pointer doesn't work.
I'm trying to assign a char value to an char pointer. The problem is
when I comment
Code:
char *a = "Some Birds Can't Fly";
the printed display is however without commenting above, it gives, lot of scrambled characters. Can you check the code and let me know what's happening.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *assign_char(char *str, char ch)
{
size_t len = strlen(str);
char *strRslt = malloc( len + 2 );
strcpy(strRslt, str);
strRslt[len] = ch;
strRslt[len+1] = '\0';
return strRslt;
}
int main(void)
{
char *b;
char *a = "Some Birds Can't Fly";
char ch = 'B';
b = assign_char(b, ch);
printf("%s\n", b);
return 0;
}
compiled with
1 Attachment(s)
Thanks for your prompt reply.
Quote:
Originally Posted by
laserlight
This is wrong:
Code:
b = assign_char(b, ch);
it should have been:
Code:
b = assign_char(a, ch);
My need is to append the ch with b, a is for demo my problem when I'm having a "a" kind of variable. Hope you get it.So isn't that correct to pass the b = assign_char(b, ch);
Quote:
Originally Posted by
laserlight
Incidentally, to avoid potential attempts to change a string literal, your code should be more const-correct, e.g., in main:
Code:
const char *a = "Some Birds Can't Fly";
and for the assign_char function:
Code:
char *assign_char(const char *str, char ch)
I tried this. However my result is same, see the attached image below, it shows what I'm getting.
Attachment 15051
Quote:
Originally Posted by
laserlight
It might be more accurate to rename assign_char to append_char.
Also, remember to free() what you malloc(). In assign_char, you should also check that malloc did not return a null pointer before you use what it returns.
Thanks a lot for the tip, I agree with you, these should definitely be implemented.
Back again to my original question, why when an unused string variable is there (a), the out put gets so wired. when I comment that "char *a = "Some Birds Can't Fly";" line. things are normal.
Thats Really making Sense after all.
Quote:
Originally Posted by
Salem
Because if you start with a pointer in main() that is uninitialised, when you get to
strcpy(strRslt, str);
you're copying garbage.
It's really that simple.
That's really impressive, thanks for pointing me out. I never thought that way.
Can you please explain me so if I have some bunch of initialized variables after main() like "int x = 1;" will my problem solved?
Actually I tried it just now, still getting the scrabbled print.