函数 returns 时 C 字符串值被销毁
C string value destroyed when function returns
所以我有这个功能:
char *ft_string(char *s, int *i) {
int j;
char *res;
j = *i;
res = NULL;
while (s[j] && s[j] != ' ' && s[j] != '\"' && s[j] != '\'' && s[j] != '$')
{
if (s[j] == '\')
ft_remove_char(s, j);
j++;
}
res = ft_substr(s, *i, j - *i);
(*i) = j - 1;
return (res);
调用 ft_remove 字符:
void ft_remove_char(char *s, int i){
char *ret;
int j;
ret = malloc((int)ft_strlen(s) * sizeof(char) + 1);
if (ret == NULL)
return ;
j = -1;
while (++j < i)
ret[j] = s[j];
i = j;
while (s[++j])
{
ret[i] = s[j];
i++;
}
ret[j - 1] = '[=12=]';
if (s)
free(s);
s = ret;
当ft_remove_char returns时,s值在ft_string中消失。
我不知道我做错了什么,我在堆上分配一个字符串,然后让 s 指向它。
C 中的参数按值传递。函数 ft_remove_char
接收指针 s
的 copy。所以,当它覆盖s
时,它不会影响ft_string
中的s
。
相反,尝试从 ft_remove_char
返回修改后的 s
并将 ft_string
中的调用更改为:
s = ft_remove_char(s, j);
这在 C 语言中非常地道。
注意:这只是回答您的问题。我尚未验证您的代码是否正确。
所以我有这个功能:
char *ft_string(char *s, int *i) {
int j;
char *res;
j = *i;
res = NULL;
while (s[j] && s[j] != ' ' && s[j] != '\"' && s[j] != '\'' && s[j] != '$')
{
if (s[j] == '\')
ft_remove_char(s, j);
j++;
}
res = ft_substr(s, *i, j - *i);
(*i) = j - 1;
return (res);
调用 ft_remove 字符:
void ft_remove_char(char *s, int i){
char *ret;
int j;
ret = malloc((int)ft_strlen(s) * sizeof(char) + 1);
if (ret == NULL)
return ;
j = -1;
while (++j < i)
ret[j] = s[j];
i = j;
while (s[++j])
{
ret[i] = s[j];
i++;
}
ret[j - 1] = '[=12=]';
if (s)
free(s);
s = ret;
当ft_remove_char returns时,s值在ft_string中消失。 我不知道我做错了什么,我在堆上分配一个字符串,然后让 s 指向它。
C 中的参数按值传递。函数 ft_remove_char
接收指针 s
的 copy。所以,当它覆盖s
时,它不会影响ft_string
中的s
。
相反,尝试从 ft_remove_char
返回修改后的 s
并将 ft_string
中的调用更改为:
s = ft_remove_char(s, j);
这在 C 语言中非常地道。
注意:这只是回答您的问题。我尚未验证您的代码是否正确。