Kevin Kevin - 19 days ago 6
C Question

How to create a Multi-Dimensional Array from a String Literal

I'm new here and I'm new to

C
too.
I have the following pointer
ptr
which points to a
String Literal
:

const char *ptr = "Hello my dear World";


What I need to do is to create a Multi-Dimensional Array which should contain those words which should result in something similar to this:

char arr[MAX_WORD][MAX_SIZE_OF_WORD] = {"Hello", "my", "dear", "World"};


What I have so far is this:

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

#define MAX_WORD 4
#define MAX_SIZE_OF_WORD 6

int main(void){
const char *ptr = "Hello my dear World";
char arr[MAX_WORD][MAX_SIZE_OF_WORD] = {0};

while ( *ptr != '\0'){
/* code here */
ptr++;
}

size_t len = sizeof arr / sizeof *arr;
for (size_t x = 0 ; x < len ; x++){
printf("%s",arr[x]);
printf("\n");
}
}


My logic was to iterate
ptr
until i reach
'\0'
and to copy those words inside
char arr[][]
, but the problem is, I don't know how to do that.

How to copy the content of
ptr
inside
arr[][]
?

Answer

Here you are.

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

#define MAX_WORD 4
#define MAX_SIZE_OF_WORD 6

void split_to_array( char ( *a )[ MAX_SIZE_OF_WORD ], size_t n, const char *s )
{
    for ( size_t i = 0; *s != '\0' && i < n; i++ )
    {
        while ( isblank( ( unsigned int )*s ) ) ++s;

        if ( *s )
        {
            const char *last = s;
            while ( ++last && !isblank( ( unsigned char )*last ) );

            size_t length = ( size_t )(last - s + 1 < MAX_SIZE_OF_WORD ? 
                            last - s + 1 :
                            MAX_SIZE_OF_WORD );

            strncpy( a[i], s, length );
            a[i][length -1] = '\0';

            s = last;
        }
    }
}

int main(void) 
{
    const char *ptr = "Hello my dear World";
    char arr[MAX_WORD][MAX_SIZE_OF_WORD] = {0};

    split_to_array( arr, MAX_WORD, ptr );

    for ( size_t i = 0; i < MAX_WORD; i++ ) puts( arr[i] );

    return 0;
}

The program output is

Hello
my
dear
World
Comments