如何用C语言指针实现一维字符数组?求助:代码无法完整输出"abcde"
Hey there! Let's tackle both your questions: how to work with strings (1D char arrays) using pointers in C, and fix that bug stopping your code from outputting "abcde" properly.
用指针操作字符串的核心要点
In C, a string is just a char array terminated by a '\0' (null character). Pointers let you directly access and manipulate this array by pointing to its first element. Here's the breakdown:
- Declare a char pointer:
char *str;– this creates a pointer, but it doesn't point to valid memory yet. - Allocate memory dynamically: Use
malloc()to reserve space for your string. Always add 1 extra byte for the null terminator, like you did withp = (char *)malloc(L+1);– that's the right move! - Access characters:
*(p + i)is exactly the same asp[i]. The pointer offset syntax (*(p+i)) makes it clear you're using pointer arithmetic to jump to the i-th character. - Never skip the null terminator: Without
'\0', functions likeprintf("%s", p)will keep reading garbage from memory until they hit a random null character – always add it at the end of your string.
Fixing Your "abcde" Output Issue
The problem in your code is leftover newline in the input buffer after reading L with scanf("%d", &L). Let me explain:
When you type 5 and press enter, the input buffer holds 5\n. scanf("%d") reads the 5 but leaves the \n behind. Then your first scanf("%c", p+i) reads this newline instead of the first character of "abcde". That means you only end up reading 4 actual characters (abcd) instead of 5, hence the incomplete output.
Two Easy Fixes
- Eat the newline with
getchar()right after readingL:
#include<stdio.h> #include<stdlib.h> int main() { int L,i; char *p; scanf("%d",&L); getchar(); // Clears the leftover newline p=(char *)malloc(L+1); for(i=0;i<L;i++) { scanf("%c",p+i); } *(p+i)='\0'; printf("%s\n", p); // Use %s to print the whole string at once free(p); // Don't forget to free allocated memory! return 0; }
- Add a space in your
scanfformat string to skip all whitespace (newlines, spaces, tabs):
#include<stdio.h> #include<stdlib.h> int main() { int L,i; char *p; scanf("%d",&L); p=(char *)malloc(L+1); for(i=0;i<L;i++) { scanf(" %c",p+i); // The space skips whitespace } *(p+i)='\0'; printf("%s\n", p); free(p); return 0; }
A quick bonus tip: Always use free(p) to release memory allocated with malloc() – it prevents memory leaks, which is a good habit to build early.
内容的提问来源于stack exchange,提问作者Tsurgi Blade

