Em đang viết bài tập sau: Nhập chuỗi st1, st2, vị trí 1 phần tử của chuỗi st1. Chèn chuỗi st2 vào chuỗi st1 từ vị trí được nhập. Em debug ko lỗi nhưng khi chạy lại báo lỗi. Mong mọi người giúp đỡ.
Code:
#include <stdio.h> #include <conio.h> #include <string.h> #include <stdlib.h> void chenchuoi(char*st1,char*st2,int n) { int m=strlen(st1),k=0; char *t1,*t2; t1=(char*)malloc(n+1); t2=(char*)malloc(m-n+1); strncpy(t1,st1,n); t1[n]='\0'; for(int i=n;i<m;i++) { t2[k]=st1[i]; ++k; } t2[m-n]='\0'; strcat(t1,st2); strcat(t1,t2); puts(t1); } void main() { int n; char *st1,*st2; st1=(char*)malloc(sizeof(st1)); st2=(char*)malloc(sizeof(st2)); printf("Nhap chuoi st1: "); gets(st1); printf("Nhap vi tri can chen: "); scanf("%d",&n); printf("Nhap chuoi can chen: "); gets(st2); chenchuoi(st1,st2,n); getch(); }
Comment