使用指针处理字符串

定义数组和指针,将指针指向数组,通过对指针所存地址的增加,对数组赋值。
#include <stdio.h>//stdio.h has also defined the size_t & sizeof

int main(void)
{
    char buffer[101];
    char *pbuffer = buffer;
    size_t index = 0;

    for( ; index<sizeof(buffer) ; index++)
    {
        if((*(pbuffer+index) = getchar()) == '\n')
        {
            //replace '\n' by '\0' at the end of the string
            *(pbuffer+index) = '\0';
            printf("%s\n",buffer);
            break;
        }
    }
    if((index == sizeof(buffer))&&(*(pbuffer+index)!='\0'))
       {
           printf("You ran out of space in the buffer.\nf");
           return 1;
       }

    //while((*pbuffer++ = getchar())!='\n');
    //*(--pbuffer)='\0';

    return 0;
}

#include <stdio.h>

int main(void)
{
    const size_t BUFFER_LEN = 512;
    int i=0;
    char buffer[BUFFER_LEN];
    char *pS[3] = {NULL};
    char *pbuffer = buffer;
    size_t index = 0;

    printf("Enter 3 messages that total less than %u characters.\n",
           BUFFER_LEN-2);

    //read the strings from the keyboard
    for(;i<3;i++)
    {
        printf("Enter %s message:\n",i>0?"another":"a");
        pS[i]=&buffer[index];//save start of string
        //read up to the end of buffer if necessary
        for(;index<BUFFER_LEN;index++)//if you read \n
            if((*(pbuffer+index)=getchar())=='\n')
            {
                *(pbuffer+index++)='\0';
                break;
            }

        //check for buffer capacity exceeded
        if((index == BUFFER_LEN)&&((*(pbuffer+index-1)!='\0')||(i<2)))
        {
            printf("\nYou ran out of space in the buffer.");
            return 1;
        }
    }
    printf("\nThe strings you entered are:\n\n");
    for(i=0;i<3;i++)
        printf("%s\n",pS[i]);

    printf("The buffer has %d characters unused.\n",
           BUFFER_LEN-index);
    return 0;
}

评论

此博客中的热门博文

清明雨凉

简记