1. 程式人生 > >C語言複製陣列

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;

因為沒有開闢記憶體,直接對指標自增會出現訪問衝突