Home > Software design >  Can't get char from string in C
Can't get char from string in C

Time:06-13

I have a function similar to this, where I want to get the char at a specific index in S. But when I try to access it, it returns a substring from the index to the end of the char[] instead of the char at the index. I'm new to C, what am I missing here?

char * test(char *S) {
    printf(&S[1]);
}

Input: "Test"

Expected Return : "e"

Actual Return: "est"

CodePudding user response:

With this code you're returning a pointer to the second character of the string, so it's like asking to print the substring starting at position 1.

In order to only print the second character in the string, you need to specify the actual value, not the pointer:

Also, since you defined your function with a char pointer return type but then you don't return anything, I think you should either put void as a return type:

void test(char *S) {
    printf("%c", S[1]);
}

or modify the return type to char for your function and return the specified char:

char test(char *S) {
    printf("%c", S[1]);
    return S[1];
}
  •  Tags:  
  • c
  • Related