简体   繁体   English

将字符分配给字符 *

[英]Assign char to char *

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?我怎样才能使最后(注释)行工作?

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 .您可以向函数添加一个检查,确保索引不在glob_str指向的字符串文字glob_str

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看到这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM