0

I am trying to make an array of modifiable length, i defined a function called "add" that should add a char to the last of the array, but this result in putchar and printf not working. Why is this happening? and how can i fix it?

the output should be "hix", and the output is apparently ""

#include <stdio.h>

typedef struct
{
    char* ptr;
    size_t len;
}
bytes;

void add(bytes text, char chr)
{
    text.ptr[text.len++] = chr;
}

bytes parse(char text[])
{
    size_t index = 0;

    while (text[index]) ++index;

    return (bytes) {text, index};
}

void print(bytes text)
{
    for (size_t index = 0; index < text.len; ++index)
    {
        putchar(text.ptr[index]);
    }
}

int main()
{
    bytes str = parse("hi");
    add(str, 'x'); // if i remove this line "print" works, but only prints "hi"
    
    print(str);

    return 0;
}
  • 1
    You cannot modify a string literal, or change the length of an array. You'll overflow the allocation anyway. You need to allocate memory dynamically and copy the string. Then when you add a character, reallocate. – Weather Vane Feb 08 '23 at 08:37

1 Answers1

0

When you try to modify string literal you will get memory overflow allocation problem.

So Your final code with allocation memory to sort the problem of Segmentation fault (core dumped)

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

typedef struct {
  char * ptr;
  size_t len;
}
bytes;

void add(bytes * text, char chr) {
  text -> ptr[text -> len++] = chr;
}

bytes parse(char text[]) {
  size_t index = 0;
  char * new_ptr = NULL;

  while (text[index]) ++index;

  new_ptr = (char * ) malloc(index + 1);
  if (new_ptr == NULL) {
    printf("Memory allocation failed!\n");
    exit(1);
  }

  for (int i = 0; i < index; i++) {
    new_ptr[i] = text[i];
  }
  new_ptr[index] = '\0';

  return (bytes) {
    new_ptr,
    index
  };
}

void print(bytes text) {
  for (size_t index = 0; index < text.len; ++index) {
    putchar(text.ptr[index]);
  }
}

int main() {
  bytes str = parse("hi");
  add( & str, 'x');

  print(str);

  free(str.ptr);

  return 0;
}

Result :

hix

You can check by compile this code on C compiler

NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22