I should copy str2 to str1, perhaps the main problem is that I should
copy only a certain index of that string (so from str2[a] to str2[b]).
It looks like you need to copy a part of one string in another character array starting from its initial position and as a result the character array shall also keep a string built from characters of the first string.
If so then the function should be declared like
char * myfunction( char str1[], const char str2[], size_t n );
that is one of parameters of your original function is redundand because using the pointer arithmetic you can always call the function like
myfunction( str1, str2 + a, b - a + 1 );
In your function implementation it seems there are typos.
void myfunction(char str1[], char str2[], int a, int b) {
int i, j;
for (i = a; i <= b; i++) {
str1 += str2[i];
}
}
For example the variable j
is not used, And in this assignment statement
str1 += str2[i];
the left operand is a pointer. So you are just increasing the pointer itself without copying anything. For example if str2[i]
contains the character 'A'
then the above statement looks like
str1 += 'A';
If there is used the ASCII character table then the statement is equivalent to
str1 += 65;
That is the address stored in the pointer str1
is increased by 65
and will point beyond the destination array.
Also in main there is no great sense to input a string in the character array str1
because as it is supposed it will be overwritten in the function.
Pay attention to the function gets
is unsafe and is not supported by the C Standard any more. Instead you should use the function fgets
.
Here is a demonstrative program that shows how the function can be written without using standard string functions.
#include <stdio.h>
#define N 50
char * myfunction( char str1[], const char str2[], size_t n )
{
char *p = str1;
while ( *str2 && n-- )
{
*p++ = *str2++;
}
*p = '\0';
return str1;
}
int main(void)
{
char str1[N];
char str2[N] = "Hello World!";
puts( str2 );
puts( myfunction( str1, str2 + 6, 6 ) );
return 0;
}
The program output is
Hello World!
World!
If you will change the function the following way
char * myfunction( char str1[], const char str2[], size_t n )
{
char *p = str1;
while ( *str2 && n )
{
*p++ = *str2++;
--n;
}
while ( n-- ) *p++ = '\0';
return str1;
}
then it will behave the same way as the standard string function strncpy
declared in the header <string.h>
which you should familiarize yourself with.