If I have understood you correctly then you need something like the following.
I used sentinel values for the both dynamically allocated arrays. You can use your own approach instead of using sentinel values.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * Seg( const char *input, char ***segs, int **tags )
{
// dynamic malloc the memory here
size_t count = strlen( input ); // this count is according to input
*segs = malloc((count + 1) * sizeof(char *));
*tags = malloc((count + 1) * sizeof(int));
for ( size_t i = 0; i < count; i++ )
{
( *segs )[i] = "abc";
}
(*segs)[count] = NULL;
for ( size_t i = 0; i < count; i++ )
{
( *tags )[i] = ( int )i;
}
(*tags)[count] = -1;
return NULL;
}
int main( void )
{
char **segs = NULL;
int *tags = NULL;
Seg( "input", &segs, &tags );
for (char **p = segs; *p; ++p)
{
printf( "%s ", *p );
}
putchar('
');
for (int *p = tags; *p != -1; ++p)
{
printf("%d ", *p);
}
putchar('
');
free(segs);
free(tags);
return 0;
}
The program output is
abc abc abc abc abc
0 1 2 3 4
After you updated your post then the function can look also the following way
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
size_t Seg( const char *input, char ***segs, int **tags )
{
// dynamic malloc the memory here
size_t count = strlen( input ); // this count is according to input
*segs = malloc(count * sizeof(char *));
*tags = malloc(count * sizeof(int));
for ( size_t i = 0; i < count; i++ )
{
( *segs )[i] = "abc";
}
for ( size_t i = 0; i < count; i++ )
{
( *tags )[i] = ( int )i;
}
return count;
}
int main( void )
{
char **segs = NULL;
int *tags = NULL;
size_t n = Seg( "input", &segs, &tags );
for (size_t i = 0; i < n; i++)
{
printf( "%s ", segs[i] );
}
putchar('
');
for (size_t i = 0; i < n; i++)
{
printf("%d ", tags[i]);
}
putchar('
');
free(segs);
free(tags);
return 0;
}
You can also add code to the function that checks whether the memory was allocated successfully.
As for your additional question then such a code like for example this
int *tags_ = malloc(n * sizeof(int));
tags = &tags_;
changes local variable tags
of the type int **
(function parameters are function local variables) instead of changing the original pointer tags
of the type int *
passed to the function by reference as an argument.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…