使用char getlastc(char*)函数返回数组末字符无输出问题排查
getlastc Function Isn't Working (And How to Fix It) Let's break down the issues in your code step by step—there are two critical problems causing the lack of output:
1. The Loop Logic is Fundamentally Flawed
Your current loop condition while(c = *array) runs only when the current character is non-null (since c gets assigned the value of *array, and the loop continues as long as that value is truthy). Inside the loop, you check if(*array++ == '\0')—but since we're already in the loop, we know *array isn't '\0'! That check will never trigger, so the function never returns from inside the loop.
2. Missing Return Statement After the Loop
When the loop exits (which happens when *array is '\0'), there's no return statement in your function. This leads to undefined behavior—the function will return some random garbage value (or nothing meaningful), which is why printf shows no valid output.
Fixed Version of getlastc
Here are two straightforward ways to rewrite the function correctly to return the last character of the string:
Option 1: Traverse to the End and Backtrack
This approach moves a pointer to the null terminator, then returns the character just before it:
#include <stdio.h> char getlastc(char* array) { // Handle empty string edge case if (*array == '\0') { return '\0'; // Or another sentinel value if needed } char* ptr = array; // Move until we hit the null terminator while (*ptr != '\0') { ptr++; } // Return the character before the null terminator return *(ptr - 1); }
Option 2: Track the Last Character as You Iterate
This version keeps updating a variable with the current character until it reaches the end:
#include <stdio.h> char getlastc(char* array) { char last_char = '\0'; // Loop until we hit the null terminator while (*array != '\0') { last_char = *array; array++; } return last_char; }
Testing the Fixed Code
Your main function is mostly fine (note that string literals like char *array1 = "Hello World"; are read-only, but since we're only reading from them here, that's not an issue). With the fixed getlastc, running your main will output:
d d
Which is correct, since the last character of "Hello World" is 'd'.
内容的提问来源于stack exchange,提问作者Ahmad Raza

