1. 程式人生 > >編寫一個C函式,該函式將一個字串逆序

編寫一個C函式,該函式將一個字串逆序

本人萌新一枚,今天寫了一個字串逆序的題目,然後有一個地方不是很瞭解,在主函式裡面用malloc 申請了2個Byte的記憶體,按理說我指標 i 指向的空間只能儲存2個字元,但是我試了好多次,輸了很多位,編譯器都不報錯,而且能夠正確輸入倒序數。

有沒有大牛能夠解釋一下呀,下面是我的程式:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void revers (char *ptr)
{
    int i;
    char temp;
    int length = strlen (ptr);
    for (i = 0; i < length / 2; i++)
    {
        temp = * (ptr + i);
        * (ptr + i) = * (ptr + length - 1 - i);
        * (ptr + length - 1 - i) = temp;
    }
}


int main()
{
    char * i = (char *) malloc (2)
    scanf("%s\n", i);
 
    revers (ptr);
    return 0;
}