I'm trying to obtain the n-th character from a string. However, it's
returning me the string from the n-th character onwards.
The function
char *test(char input[],int position){
does not return a character. It returns a pointer.
Moreover the function has a memory leak because at first there is allocated memory and its address is assigned to the pointer result
and then the pointer is reassigned
char *result= malloc(sizeof(char)*100);
result=&input[position];
So the address of the allocated memory is lost.
Apart from this the parameter position
can have a value that exceeds the length of the passed string. So the function can invoke undefined behavior.
If the function returns a pointer to a character then to output the pointed character you need 1) to dereference the pointer and 2) to use the conversion specifier %c
instead of %s
in a call of printf
.
Also as the passed string is not being changed within the function then the corresponding parameter should be declared with the qualifier const
.
The function can be declared and defined the following way
#include <string.h>
#include <stdio.h>
char * test( const char input[], size_t position )
{
char *result = NULL;
if ( position <= strlen( input ) )
{
result = ( char * )( input + position );
}
return result;
}
And in main you should write
char *k;
k = test( "abcdefghi\n", 3 );
if ( k != NULL ) printf( "%c\n", *k );