EDIT*: I am aware there are similar questions, but since this is a practice assignment, the function signatures are given and i am only allowed to change the function bodies. Hence i cannot change the function parameters or the return types as say the answers on similar threads. Thanks in advance!
i am really confused about a program i am writing. I am basically writing a function that takes two pointers to structures, the structures have an int component and a character array component. The function appends the two character array components to return a struct (something like the strcat). The thing is, while the array part of the struct get updated by the function, the int part does not. Can anyone explain why? The function newText creates a new struct text and sets the array of the struct as the parameter of the function. It also sets the capacity = 24. If the length of the string parameter is larger than 24, it doubles the capacity until it fits. The append function appends the two strings, then calls newText with the new appended string and sets the t1 equal to the return value of newText. I have print statements at the end of the append function to show me that it works and the values are correct, however in main after i call the function, t->capacity becomes 24 again instead of 48 while t-> content is correct. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
struct text { int capacity; char *content; };
typedef struct text text;
text *newText(char *s) {
text *t = malloc(sizeof(text));
t->capacity = 24;
while (strlen(s) + 1 > t->capacity) {t->capacity = t->capacity * 2;}
t->content = malloc(t->capacity);
strcpy(t->content, s);
return t;
}
void append(text *t1, text *t2) {
int length1 = strlen(t1->content);
int length2 = strlen(t2->content);
int lengths = length1 + length2;
for (int i = length1; i < length1 + length2; i++){
t1->content[i] = t2->content[i - length1];
t1->content[i + 1] = '\0'; }
char text[100];
strcpy(text, t1->content);
t1 = newText(text);
printf("%s \n", t1->content);
printf("%d \n", t1->capacity);
}
int main () {
text *t = malloc(sizeof(text));
text *t1 = malloc(sizeof(text));
t = newText("carpet");
t1 = newText("789012345678901234");
append(t, t1);
printf("%d\n", t->capacity);
}