You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言指针实现一维字符数组?求助:代码无法完整输出"abcde"

用C语言指针实现字符串&代码问题修复

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 with p = (char *)malloc(L+1); – that's the right move!
  • Access characters: *(p + i) is exactly the same as p[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 like printf("%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

  1. Eat the newline with getchar() right after reading L:
#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;
}
  1. Add a space in your scanf format 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:37:31