C语言复制数组
直接上代码,分别是栈上开辟内存,堆上开辟内存
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 void test01(){ 5 char filename[100]; 6 7 printf("请输入视频路径:\n"); 8 scanf("%s", filename); 9 10 char *out_filename = malloc(sizeof(char)* 200); 11 memset(out_filename, 0, sizeof(char)* 200); 12 int pos = 0; 13 for (int i = 0; i < strlen(filename) - 4; ++i){ 14 out_filename[pos++] = filename[i]; 15 } 16 out_filename[pos] = '\0'; //不写\0会出现烫烫烫乱码 17 strcat(out_filename, "_out.avi"); 18 printf("%s\n", out_filename); 19 free(out_filename); 20 out_filename = NULL; 21 } 22 23 void test02(){ 24 char filename[100]; 25 26 printf("请输入视频路径:\n"); 27 scanf("%s", filename); 28 29 char tmp[100] = { 0 }; 30 int pos = 0; 31 for (int i = 0; i < strlen(filename) - 4; ++i){ 32 tmp[pos++] = filename[i]; 33 } 34 tmp[pos] = '\0'; //不写\0会出现烫烫烫乱码 35 strcat(tmp, "_out.avi"); 36 37 printf("%s\n", tmp); 38 } 39 40 int main(){ 41 42 test01(); 43 test02(); 44 45 system("pause"); 46 return 0; 47 }
如果是用指针来复制数组,不要用以下代码
char *out_filename = 0;
因为没有开辟内存,直接对指针自增会出现访问冲突