我是新来的,我也是C
的新手。
我有以下指针ptr
指向String Literal
:
const char *ptr = "Hello my dear World";
我需要做的是创建一个多维数组,其中应该包含那些应该产生类似内容的单词:
char arr[MAX_WORD][MAX_SIZE_OF_WORD] = {"Hello", "my", "dear", "World"};
到目前为止我所拥有的是:
#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");
}
}
我的逻辑是迭代ptr
直到我到达'\0'
并将这些字词复制到char arr[][]
中,但问题是,我不知道该怎么做。
如何在ptr
内复制arr[][]
的内容?
答案 0 :(得分:0)
你在这里。
#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;
}
程序输出
Hello
my
dear
World