使用Realloc调整char的大小**

时间:2015-05-15 02:48:01

标签: c realloc

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已更改
  • 带有记忆地址的
  • l->corrente->str = ""0x605050

我需要什么:
1)更改l->corrente->str中的my_func()值;
2)或者不知何故,在strcat之后将*s值更改为新值。并保持l->corrente->str相同。

1 个答案:

答案 0 :(得分:1)

如果我理解正确并且您希望在保持*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.

void - 保留*s,在*s2

中连接

而不是返回指针,my_func的此实现仍然是void并且ss2s保持不变,但是连接{{1}在"ss2"中。如果我再次误解,请告诉我。

s2

<强>输出

#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);
}