K
K
Korifa2020-04-21 15:00:12
C++ / C#
Korifa, 2020-04-21 15:00:12

How to solve this task si?

Please tell me how to solve the following problem.
It is necessary to fill the array with text from the keyboard, then replace the line / lines in this array with the text in the variable.
I declared a char array variable.
Then I filled the array with getchar() in a loop.
The next step was to check each character of the array, if it matches the desired one, then check the line to the end in the inner loop.
In general, I can not increase the volume of the array using realloc. So that I can replace or insert a line.
Realloc returns empty block of memory, doesn't store data?
I thought I would increase the volume of the array and move some of the text to the right in order to insert new text.
Or does it not work out and you have to copy it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-04-21
@Korifa

First you need to understand that the memory on the stack is managed by the compiler, and for each function this memory has a fixed size. And all because there are no variables in the assembler into which our C code is compiled, instead of them the compiler will simply put offsets from the pointer to the end of the stack at the start of the function. It is for this compiler that it is important to know the sizes of all entities on the stack.
This size cannot be changed at runtime, so the only way to solve this problem with an array of characters on the stack is to allocate an array with enough memory to cover both the original string and the inserted substring.
But the memory in the heap is dynamic. And all allocations work with it. And most importantly, we can allocate it at runtime as needed.
Considering that arrays in C are essentially sugar over pointers, you can safely declare to your teacher that a pointer to several consecutive chars on the heap and a char array are one and the same.
In general, normally I would declare a structure like this:

typedef struct {
  char* buffer;
  size_t capacity;
  size_t length;
} string;
and then I would work with it, at the same time breaking the code into small functions. But programming teachers are far from development, and apart from their labs, programming is not a boom-boom for the most part. And in the comments to the question it was about the fact that structures are impossible ...
Therefore, the solution is head-on and in the style of a university lab:
#include <stdio.h>
#include <stdlib.h>

int main() {
  size_t capacity = 1 << 4; // на старте буду выделять 16 байт
  size_t length = 0; // строка пока пустая, поэтому 0
  char* str = malloc(capacity);
  if (str == NULL) { // с памятью в куче может и облом быть
    return 1; // вернем код ошибки
  }
  printf("Write string and press ENTER to continue:\n");
  while(1) { // читать символы будем до скончания веков ))
    char c = getchar();
    if(c == 13 || c == 10) break; // ну или пока юзер не нажмет ентер
    length++; // увеличим счетчик символов
    if(length > capacity) { // если новый символ не влазит в выделеную память
      capacity <<= 1; // то удвоим ее
      char* new_str = realloc(str, capacity); // и перевыделим
      if (new_str == NULL) { // опять чекнем, вдруг облом
        free(str); // ресурсы надо освобождать
        return 1; // вернем код ошибки
      }
      str = new_str; // в str теперь невалидный указатель, можем его заменить
    }
    str[length - 1] = c; // запомним считанный символ
  }
  // Здесь решение с вставкой подстроки
  // с учетом того, что у нас строка str
  // с длиной length и выделеной памятью под нее capacity
  free(str); // ресурсы надо освобождать
  return 0; // вернем код успешного завершения
}
with the insertion of a substring I hope you can handle it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question