使用 Realloc 调整字符大小 **

Using Realloc to resize a char **

typedef struct element element;
struct element{
    dado_t str;
    elemento* preview;
    elemento* next;
};

typedef struct lista2 lista2;
struct lista2{
    elemento* primeiro;
    elemento* ultimo;
    elemento* corrente;
};


void caller(lista2* l){
    char *s = l->corrente->str;
    char *s2 = l->corrente->next->str;
    my_func(&s, &s2);
}

void my_func(char **s, char**s2){
    size_t len = strlen(*s);
    size_t len2 = strlen(*s2);
    char *w = *s;
    char *tmp = realloc(w, len + len2 + 1); //PROBLEM HERE
    if(tmp != NULL)
       *s = tmp;
    else
        *s = NULL;
    strcat(*s, *s2);
}  

当我 运行 我的代码(在 realloc() 之前):

到目前为止一切都很好。
现在状态 after realloc(赋值前 *s = tmp):

还可以吧?现在我在 *s = tmp 之后得到的是:

我需要的:
1) 更改 l->corrente->str 中的值 my_func();
2) 或者以某种方式,将 *s 值更改为 strcat 之后的新值。并保持 l->corrente->str 不变。

如果我对你的理解是正确的,并且你想在保持 *sl->corrente->str 相同的同时创建一个连接值,那么 my_func [=41 会更有意义=] 指向新连接字符串的指针,同时保持两个输入字符串不变。如果我不明白你想做什么,请发表评论。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *my_func(char *s, char*s2);

int main (void) {

    char *a = strdup ("I like coffee.");
    char *b = strdup ("I like tea.");

    char *c = my_func (a, b);

    printf ("\n a: %s\n b: %s\n c: %s\n\n", a, b, c);

    return 0;
}

char *my_func(char *s, char*s2)
{
    size_t len = strlen(s);
    size_t len2 = strlen(s2);
    char *w = strdup (s);

    char *tmp = realloc(w, len + len2 + 1); //PROBLEM HERE

    if(!tmp) {
        fprintf (stderr, "%s() error: realloc failed.\n", __func__);
        return NULL;
    }

    w = tmp;
    strcat(w, s2);

    return w;
}

输出

$ ./bin/realloc_post

 a: I like coffee.
 b: I like tea.
 c: I like coffee.I like tea.

void - 保留 *s,在 *s2

中连接

而不是 returning 指针,my_func 的这个实现仍然是 void 并采用 ss2,保持 s不变,但在 s2 中连接 "ss2"。如果我又误会了,请告诉我。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void my_func(char **s, char **s2);

int main (void) {

    char *a = strdup ("I like coffee.");
    char *b = strdup ("I like tea.");

    my_func (&a, &b);

    printf ("\n a: %s\n b: %s\n\n", a, b);

    free (a);
    free (b);

    return 0;
}

void my_func(char **s, char **s2)
{
    size_t len = strlen(*s);
    size_t len2 = strlen(*s2);
    char *w = strdup (*s);
    char *p = *s2;          /* save start address to free */

    char *tmp = realloc(w, len + len2 + 1);

    if(!tmp) {
        fprintf (stderr, "%s() error: realloc failed.\n", __func__);
        return;
    }

    strcat(tmp, *s2);
    *s2 = tmp;
    free (p);
}

输出

$ ./bin/realloc_post

 a: I like coffee.
 b: I like coffee.I like tea.