Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C语言中,我们如何使用指针代替数组来改变大小写并打印长度?_C - Fatal编程技术网

在C语言中,我们如何使用指针代替数组来改变大小写并打印长度?

在C语言中,我们如何使用指针代替数组来改变大小写并打印长度?,c,C,我正在写一个程序,将小写句子转换成大写。我还想知道绳子的长度。我是通过数组和指针来实现的。计划如下:- /* Program to convert the lower case sentence in upper case sentence and also calculate the length of the string */ #include<stdio.h> main() { char fac='a'-'A',ch[20],*ptr,a[20];int i=0,co

我正在写一个程序,将小写句子转换成大写。我还想知道绳子的长度。我是通过数组和指针来实现的。计划如下:-

/* Program to convert the lower case sentence in upper case sentence and also calculate the length of the string */
#include<stdio.h>
main()
{
    char fac='a'-'A',ch[20],*ptr,a[20];int i=0,count=0;
    ptr=ch;

    /* Changing case and printing length by using pointers */
    printf("Enter the required string");
    gets(ptr);
    while(*ptr!='\0')
    {
        *ptr+=fac;   // LINE #1
        ptr++;
        count++;
    }
    puts(ptr);
    printf("%d",count);

    /* Changing case by using arrays */
    printf("Enter the required string");
    gets(ch);
    while(ch[i]!='\0')
    {
        ch[i]+=fac;
        i++;
    }
    puts(ch);
return 0;
}
/*将小写语句转换为大写语句并计算字符串长度的程序*/
#包括
main()
{
char fac='a'-'a',ch[20],*ptr,a[20];int i=0,count=0;
ptr=ch;
/*使用指针更改大小写和打印长度*/
printf(“输入所需字符串”);
获取(ptr);
而(*ptr!='\0')
{
*ptr+=fac;//第1行
ptr++;
计数++;
}
看跌期权(ptr);
printf(“%d”,计数);
/*使用数组更改大小写*/
printf(“输入所需字符串”);
获取(ch);
而(ch[i]!='\0')
{
ch[i]+=fac;
i++;
}
看跌期权(ch);
返回0;
}

这个程序在打印长度(指针部分)和更改大小写(数组部分)方面工作得非常好。问题是指针的大小写转换。我的印象是第#1行将指针“ptr”处存储的值增加所需的数字(32)。但是屏幕上什么也没有发生。为什么会这样?请帮忙

将ptr递增到循环中字符串的末尾,然后使用ptr打印出字符串-它位于字符串的末尾,所以什么也得不到。将其更改为puts(ch),我认为它会起作用。哦,是的-我想你想要-=不+=用于从小写到大写的转换


顺便说一句,在递增之前,您可能需要确保字符在正确的输入范围内。

指针指向内存地址。您需要读取地址处的字符,而不是地址本身。当然,如果您更改通过指针创建的char变量的大小写,您将更改内存中的实际字符。如果这不是您想要的,您需要创建一个临时字符数组或字符串

看看你的循环:

while(*ptr!='\0')
{
    ...
    ptr++;
    ...
}
puts(ptr);
您已经递增了
ptr
,直到它的值是nul终止符的地址!所以你打印的只是一个空字符串

相反,将
ptr
的初始值存储在循环之前的某个位置:

char *initial_ptr;
...
initial_ptr = ptr;
while(*ptr!='\0')
{
    ...
    ptr++;
    ...
}
puts(initial_ptr);

谢谢你的回答。成功了。但我不能理解你们的逻辑,然后你们用ptr打印出字符串——它在字符串的末尾,所以你们什么也得不到。我仅在开始时将ch的值复制到ptr中。此外,我将值存储在单个地址中。那么,为什么这是一个问题呢?但是在循环中,你的ptr++操作改变了ptr的值;您需要制作一份原始ptr的副本。