关于#c语言#的问题,使用未初始化的内存q ?


#include 
#include 

void f(char* p)
{
    char max , * q;
    int i = 0;
    max = p[i];
    while (p[i] != '\0')
    
        
        {
            if (max < p[i])
            {max = p[i]; q = p + 1; }

            i++;
        }
        while (q > p)
        
            {    *q = *(q - 1); q--; }

            p[0] = max;
            
}


int mani()
{
    char str[80] = "abcde";

    f(str);

    puts(str);

    printf("\n");


    return 0;
}

这段代码有点问题:

  1. 使用未初始化的内存q,如果p数组中不存在比它大的元素,那么q指针将不指向任何内存位置。
  2. 代码中的 "q = p + 1;" 应该是 "q = p + i;".
  3. while循环内的逻辑应该是移动q的值而不是q的地址。
#include <stdio.h>
#include <string.h>
 
void f(char* p)
{
    char max, *q;
    int i = 0;
    max = p[i];
    q = p;
    while (p[i] != '\0')
    {
        if (max < p[i])
        {
            max = p[i];
            q = p + i;
        }
        i++;
    }
    if (q > p)
    {
        while (q < p + strlen(p))
        {
            *(q - 1) = *q;
            q++;
        }
        *(q - 1) = max;
    }
}
 
int main()
{
    char str[80] = "abcde";
 
    f(str);
 
    puts(str);
 
    printf("\n");
 
    return 0;
}

我修改了下,你试试