-3

I need an entire string to be one char of another string.

const char *const_string = "FOOBAR";
char *character_string = malloc(1024);
// character_string = const_string[3];

How can I make the last (commented) line work?

MD XF
  • 7,860
  • 7
  • 40
  • 71

2 Answers2

3

It seems you mean the following

void do_something(char *str, int idx)
{
    str[0] = glob_str[idx];
    str[1] = '\0';
}

You can add a check to the function that the index is not outside the string literal pointed to by glob_str.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • @Redesign Vlad's code should work. Please post the entire program you are running which gives you just an empty string. – jforberg Jan 11 '17 at 00:48
  • Oops, never mind. I had a leftover piece of code that was messing me up. – MD XF Jan 11 '17 at 00:52
  • @Redesign If your problem is resolved, please do one of (1) accept Vlad's answer (2) delete your question (3) write some kind of note at the top of your question. This is so that we know it's solved and people don't have to spend time reading it. – jforberg Jan 11 '17 at 00:54
0

Given

char *glob_str = "test test";  // glob_str is literal string and cannot be modified

then

glob_str[0] = val; // modification won't work

You need to change to

char glob_str[] = "test test";

See this question

Community
  • 1
  • 1
artm
  • 17,291
  • 6
  • 38
  • 54
  • You're not wrong, but I don't think that is wht OP is trying to do. I think he wants to set his malloc'd buffer to just { glob_str[0], '\0', ... } – jforberg Jan 11 '17 at 00:46