Search code examples
csubstringc-stringsfunction-definition

How can I access the certain indexes of string using the function?


I was practicing and found some exercise on the internet and it says that 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]). Therefore A and B should be entered so they reduce the range of copied indexes to str1. So here I used the function method to tackle this problem but something went wrong. So I don't get why function does not work, there must be a big mistake in my understanding or I did it all wrong.

#include <stdio.h>
#include <string.h>

#define N 50

void myfunction(char str1[], char str2[], int a, int b);

int main() {
    char str1[N], str2[N];
    int a, b;
    printf("please input str1:");
    gets(str1);
    printf("please input str2:");
    gets(str2);
    printf("please input a and b:");
    scanf("%d%d", &a, &b);
    printf("str2=%s, str1=%s", str2, str1);
    myfunction(str1, str2, a, b);
    return 0;
}

void myfunction(char str1[], char str2[], int a, int b) {
    int i, j;
    for (i = a; i <= b; i++) {
        str1 += str2[i];
    }
}

Solution

  • There are multiple problems in your program:

    • you should not use gets()
    • myfunction just increments str1 instead of copying characters.
    • you should output the resulting string.

    Here is modified version:

    #include <stdio.h>
    #include <string.h>
    
    #define N  50
    
    void myfunction(char str1[], char str2[], int a, int b);
    
    // safe replacement for gets()
    char *mygets(char *buf, size_t n) {
        int c;
        size_t i;
        while ((c = getchar()) != '\n') {
            if (c == EOF) {
                if (i == 0)
                    return NULL;
                break;
            }
            if (i + 1 < n)
                buf[i++] = c;
        }
        if (i < n) {
            buf[i] = '\0';
        }
        return buf;
    }
    
    int main() {
        char str1[N], str2[N];
        int a, b;
    
        printf("please input str1: ");
        if (!mygets(str1, sizeof str1))
            return 1;
        printf("please input str2: ");
        if (!mygets(str2, sizeof str2))
            return 1;
        printf("please input a and b: ");
        if (scanf("%d%d", &a, &b) != 2)
            return 1;
        printf("str2=%s, str1=%s\n", str2, str1);
        myfunction(str1, str2, a, b);
        printf("str1=%s\n", str1);
        return 0;
    }
    
    void myfunction(char str1[], char str2[], int a, int b) {
        int len1 = strlen(str1);
        int len2 = strlen(str2);
        int i, j;
        if (a < 0)
            a = 0;
        if (b > len2)
            b = len2;
        for (i = 0, j = a; j <= b; i++, j++) {
            str1[i] = str2[j];
        }
        if (i > len1) {
            /* do not truncate str1 but set the null terminator if needed */
            str1[i] = '\0';
        }
    }