c语言有关指针的练习

指针类型练习:
将传入的字符串str1中从第index个字符开始的全部字符复制到字符串str2中。

注意: index 必须小于 字符串的长度。复制时, 包含第index个字符.

#include 

void strmcpy (char *str1, int index, char *str2) {
  
    int j = 0;
    int i = index-1;
    for (; str1[i] != '\0'; i++,j++) {
        str2[j] = str1[i];
    }
}
int main () {
    char str1[100] = "I am a student. I like programming.", str2[100];
    int index = 10;
    strmcpy(str1, index, str2);
    printf("%s", str2);
    return 0;
}


运行结果会多出字符

需要在字符串最后加上'\0'

#include<stdio.h>
void strmcpy (char *str1, int index, char *str2) {
    int j = 0;
    int i = index-1;
    for (; str1[i] != '\0'; i++,j++) {
        str2[j] = str1[i];
    }
    str2[j]='\0';
}
int main () {
    char str1[100] = "I am a student. I like programming.", str2[100];
    int index = 10;
    strmcpy(str1, index, str2);
    printf("%s", str2);
    return 0;
}