The code has some problems. The main thing is to use the ==
operator to compare strings . In C a string is just a string of characters and needs a function of its own to compare all of them and return if it is greater, less than or equal. This function is strncmp()
. In fact any language needs to do so, but some hide it in the operator, but that is another matter and I will not go into details.
Another problem with this code is trying to return a local variable. This is not possible since content in the stack may no longer be available. It has compiler that lets you do, which is bad since there is great possibility of memory corruption. In the compiler I used, neither compile.
So the solution is to pass a buffer to the function with pre-allocated memory. So whoever needs the text allocates what they want and releases if necessary. It is only necessary to use malloc()
. In some cases you can use a array instead of the pointer and dynamic allocation.
I could even do the allocation inside the function and return that pointer, but this is usually bad because the programmer may forget that he needs to do the release. It is an asymmetric thing, the function allocates and another function takes care of the release.
I did return the buffer itself so that the function could be used as an expression as well, but if that was never necessary (unlikely in real code), it could return nothing, since the buffer is done by a pointer, so it is a reference to the actual object.
Note that I left the function simplified. This function is not secure, nothing guarantees that enough memory has been allocated to fit substring . At the moment nothing prevents the end being smaller than the beginning, which would be a mistake. It would be nice to improve it to handle these things.
I understand this is an exercise, but using memcpy()
is more appropriate in this situation than making a tie on its own.
There was another problem adding the end and beginning of string . Now there is no more, but if this were still in the code, it would be wrong, it's the opposite, it should be a difference.
Avoid using unsigned type unnecessarily .
It has small code organizations that I did too.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *substring(char *str, char *buf, int start, int end) {
for (int i = start; i < end; i++)
buf[i] = str[i];
return buf;
}
int main() {
char *texto = malloc(6);
if (strncmp(substring("Hello World", texto, 0, 5), "Hello", 5) == 0)
printf("yep");
free(texto);
return 0;
}
See running on ideone and on CodingGround .
In C ++ everything would be different because it has a string "native."