c 二維數組動態分配和釋放


c動態語言

函數聲明的頭文件在<stdlib.h>

 

 

 使用malloc函數為字符串分配內存 --》記得釋放內存 free()

 

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

char *concat(const char *s1, const char *s2);

int main(void) {
    char *p;
    p = concat("abc", "def");
    printf("%s\n", p); //abcdef
    return 0;
}

char *concat(const char *s1, const char *s2) {

    char *result;

    result = malloc(strlen(s1) + strlen(s2) + 1);
    if (result == NULL) {
        printf("Error: malloc failed in concat\n");
        exit(EXIT_FAILURE);
    }
    strcpy(result, s1);
    strcat(result, s2); //放數據
    return result;
}

 

 利用動態內存,字符串數組

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

#define MAX_REMIND 50
#define MSG_LEN 60

int read_line(char str[], int n);

int main() {
    char *reminders[MAX_REMIND]; //定義字符串數組
    char day_str[3], msg_str[MSG_LEN + 1]; // day_str是為了轉換日期用,msg_str是存儲字符串,存進數組用
    int day, i, j, num_remind = 0;

    for (;;) {
        if (num_remind == MAX_REMIND) {
            printf("-- No space left --\n");
            break;
        }
        printf("Enter day and reminder: ");
        scanf("%2d", &day);
        if (day == 0)
            break;
        sprintf(day_str, "%2d", day); //把day轉換成字符串
        read_line(msg_str, MSG_LEN); //輸入字符,變成字符串

/*        for (i = 0; i < num_remind; i++) { // num_remind記錄了有多少個字符串,這個步驟校驗有問題,應該放到下面去
            printf("ii: %d\n",i);

            if (strcmp(day_str, reminders[i]) < 0)
                break;
        }
        for (j = num_remind; j < i; j++)
            reminders[j] = reminders[j - 1];*/
        
        reminders[i] = malloc(2 + strlen(msg_str) + 1); //創建動態內存
        if (reminders[i] == NULL) {
            printf("-- No space left --\n");
            break;
        }
//        printf("i: %d\n", i);
        strcpy(reminders[i], day_str);
        strcat(reminders[i], msg_str); // 放數據
        i++;
        num_remind++;
    }
    printf("\nDay Reminder \n");
    for (i = 0; i < num_remind; i++) {
        printf(" %s\n", reminders[i]);
    }
    return 0;
}

int read_line(char str[], int n) {
    char ch;
    int i = 0;
    while ((ch = getchar()) != '\n')
        if (i < n)
            str[i++] = ch;
    str[i] = '\0';
    return i;
}

 

 

一、 已知第二維

 

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

#define MAX_REMIND 50
#define MSG_LEN 60


int main() {
    char (*a)[MSG_LEN + 1];
    a = (char (*)[MSG_LEN]) malloc(sizeof(char *) * MAX_REMIND);
    strcpy(a[0], "abcd");
    printf("%s\n", a[0]); //abcd;
    free(a);
    a = NULL; //防止野指針
    return 0;
}

// 優化后的寫法
int main() {

    char (*a)[MSG_LEN + 1] = malloc(MSG_LEN + 1);
    if (a == NULL) {
        printf("malloc error");
        exit(1);
    }

    strcpy(a, "abcd");
    printf("a = %s\n", a);

    free(a);
    a = NULL;
    return 0;
}

 

二、 已知第二維

 

三、 已知第一維, 一次分配內存(保證內存的連續性)

 

四、兩維都未知

 

 五、兩維都未知, 一次分配內存(保證內存的連續性)

 

 

 

 注意:靜態二維數組作為函數參數傳遞

 

如果采用上述幾種方法動態分配二維數組,那么將對應的數據類型作為函數參數就可以了。這里討論靜態二維數組作為函數參數傳遞,即按照以下的調用方式:

int a[2][3];
func(a);

 

C語言中將靜態二維數組作為參數傳遞比較麻煩,一般需要指明第二維的長度,如果不給定第二維長度,則只能先將其作為一維指針傳遞,然后利用二維數組的線性存儲特性,在函數體內轉化為對指定元素的訪問。
首先寫好測試代碼,以驗證參數傳遞的正確性:
(1)給定第二維長度

Code-11
void func(int a[][N])
{
printf("%d\n", a[1][2]);
} 

(2)不給定第二維長度

Code-12
void func(int* a)
{
printf("%d\n", a[1 * N + 2]);//計算元素位置
} 

注意:使用該函數時需要將二維數組首地址強制轉換為一維指針,即func((int*)a);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM