日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C語言程序設計之指針的應用詳解_C 語言

作者:暢游星辰大海 ? 更新時間: 2022-12-14 編程語言

第一關:數組倒置

程序功能是通過調用reverse()函數按逆序重新放置數組a中的元素值,請補全程序。

測試輸入: 0 1 2 3 4 5 6 7 8 9

預期輸出: 9 8 7 6 5 4 3 2 1 0

#include "stdio.h"
#define N 10
void reverse(int *p, int a, int b)
{
    int c;
    /***** 請在以下一行填寫代碼 *****/
    while (a<b)
    {
        c=*(p+a);
    /***** 請在以下一行填寫代碼 *****/
        *(p+a)=*(p+b);
        *(p+b)=c;
        a++;
    /***** 請在以下一行填寫代碼 *****/
        b--;        
    }
}
int main()
{
    int a[N], i;
    for (i=0; i<N; i++)
    /***** 請在以下一行填寫代碼 *****/
        scanf("%d",&a[i]);
    
    reverse(a, 0, N-1);//傳入首元素地址,首元素下表,末元素下標
    for (i=0; i<N; i++)
    /***** 請在以下一行填寫代碼 *****/
        printf("%d ",a[i]);
        
    printf("\n");
    return 0;
}

注意:p+1指向數組的下一個元素,而不是簡單的使使指針變量p的值+1

第二關:字符排序

對某一個長度為7個字符的字符串, 除首、尾字符之外,要求對中間的5個字符按ASCII碼降序排列

測試輸入: CEAedca

預期輸出: CedcEAa

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int fun(char *s, int num)
{
    char ch;
    int i, j;
    for(i = 1 ; i < num-1 ; i++)
        for(j = i + 1 ; j < 6 ; j++)
        {
          /***** 請在以下一行填寫代碼 *****/
            if(s[i]<s[j])    
            {
                ch = *(s + j);
                *(s + j) = *(s +i);
                *(s + i) = ch;
            }
        }
}
int main()
{
    char s[10];
    scanf("%s",s);
    /***** 請在以下一行填寫代碼 *****/
    fun(s,7);
    printf("%s",s);
    return 0;
}

第三關:找最長串

本關任務:給定程序中函數fun的功能是從N個字符串中找出最長的那個串,并將其地址作為函數值返回。N個字符串在主函數中輸入,并放入一個字符串數組中。請改正程序中的錯誤,使它能得出正確結果。注意:不要改動main函數,不得增行或刪行,也不得更改程序的結構。

測試輸入: a bb ccc dddd eeeee

預期輸出:

The 5 string :
a
bb
ccc
dddd
eeeee
The longest string :
eeeee

#include <stdio.h>
#include <string.h>
#define N 5
#define M 81
/***** 以下一行有錯誤 *****/
char* fun(char (*sq)[M])
 
{
    int i; char *sp;
    sp=sq[0];
    for(i=0;i<N;i++)
        if(strlen(sp)<strlen(sq[i]))
            sp=sq[i];
        
/***** 以下一行有錯誤 *****/
    return sp;
    
}
int main()
{
    char str[N][M], *longest; int i;
    
    
    for(i=0; i<N; i++)
        scanf("%s",str[i]);
    
    printf("The %d string :\n",N);
    
    for(i=0; i<N; i++) 
        puts(str[i]);
    longest=fun(str);
        
    printf("The longest string :\n");
    puts(longest);
    
    return 0;
}

第四關:星號轉移

規定輸入的字符串中只包含字母和*號。給定程序的功能是將字符串中的前導*號全部移到字符串的尾部。請將程序補充完整,使其能正確運行得出結果。

測試輸入: ***abcd

預期輸出: abcd***

#include <stdio.h>
void  fun( char *a )
{
    int i=0,n=0;
    char *p;
    p=a;
    while (*p=='*')
    {
        n++;     //統計字符串中前導*號的個數
        p++;
    }
    while(*p)
    {
        a[i]=*p; //把前導*號之后的字符全部前移
        i++; 
        p++;
    }
    while(n!=0)
    {
        a[i]='*'; //把統計*號個數補到字符串的末尾
        i++;
        n--;
    }
    a[i]='\0';
}
int main()
{
    char s[81];
    int n=0;
    scanf("%s",s);
    fun(s);
    printf("The string  after oveing: \n");
    puts(s);
    return 0;
}

原文鏈接:https://blog.csdn.net/m0_73222051/article/details/127895610

欄目分類
最近更新