0
0

More than 1 year has passed since last update.

文字列の二次元配列をポインタのポインタに変換する方法

Last updated at Posted at 2023-06-22

C言語で文字列の二次元配列をポインタのポインタに変換する方法です。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE 3
#define LEN 10

int main(void){
    char str_array[ARRAY_SIZE][LEN] = {
        "neko",
        "inu",
        "usagi"
    };

    char** str_pp = NULL;

    str_pp = (char**)malloc(sizeof(char*) * ARRAY_SIZE);
    if(str_pp == NULL){
        return EXIT_FAILURE;
    }

    for(int i = 0; i< ARRAY_SIZE; i++){
        str_pp[i] = (char*)malloc(sizeof(char) * LEN);
        if(str_pp[i] == NULL){
            return EXIT_FAILURE;
        }
        strncpy(str_pp[i], str_array[i], LEN);
    }

    for(int i = 0; i< ARRAY_SIZE; i++){
        fprintf(stdout, "%s\n", str_pp[i]);
    }

    for(int i=0; i<ARRAY_SIZE;i++){
        free(str_pp[i]);
    }

    free(str_pp);

    return EXIT_SUCCESS;
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0