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()之前):
*w = "I Like Coffe"内存地址:0x605050
*s = "I Like Coffe"内存地址:0x605050
l->corrente->str = "I Like Coffe"内存地址:0x605050
到目前为止一切都很好。
现在状态在realloc之后(分配*s = tmp)之前):
*w = ""内存地址:0x605050
*s = ""内存地址:0x605050
l->corrente->str = ""内存地址:0x605050
还好吧?现在我得到的是:
*s = tmp内存地址:*w = ""
0x605050内存地址已更改
*s = "I Like Coffe"内存地址:0x605160
我需要的是:
1)在l->corrente->str = ""中改变0x605050值;
2)或以某种方式,将l->corrente->str值更改为strcat后的新值。并保持my_func()不变。

最佳答案

如果我理解正确,并且希望在保持*sl->corrente->str不变的情况下创建连接值,那么让my_func返回指向新的连接字符串的指针,同时保持两个输入字符串不变会更有意义。如果我不明白你想做什么,请留言。

#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.

保留空位*s,连接到*s2
这个my_func的实现不返回指针,而是保持void不变,并接受ss2,但在s中连接"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.

09-20 04:27