ft_strncmp.c - chanhl22/libft GitHub Wiki

  1 /* ************************************************************************** */
  2 /*                                                                            */
  3 /*                                                        :::      ::::::::   */
  4 /*   ft_strncmp.c                                       :+:      :+:    :+:   */
  5 /*                                                    +:+ +:+         +:+     */
  6 /*   By: chanhlee <[email protected].>       +#+  +:+       +#+        */
  7 /*                                                +#+#+#+#+#+   +#+           */
  8 /*   Created: 2021/01/20 11:49:50 by chanhlee          #+#    #+#             */
  9 /*   Updated: 2021/02/01 23:11:49 by chanhlee         ###   ########.fr       */
 10 /*                                                                            */
 11 /* ************************************************************************** */
 12 
 13 #include "libft.h"
 14 
 15 int ft_strncmp(const char *s1, const char *s2, size_t n)
 16 {
 17     unsigned char *ptr_s1;
 18     unsigned char *ptr_s2;
 19     size_t i;
 20 
 21     ptr_s1 = (unsigned char *)s1;
 22     ptr_s2 = (unsigned char *)s2;
 23     i = 0;
 24     while (s1[i] != '\0' && s2[i] != '\0' && i < n && ptr_s1[i] == ptr_s2[i]) // s1๊ณผ s2๊ฐ€ null์ด ์•„๋‹๋•Œ, n์œผ๋กœ ์นด์šดํŠธ๋ฅผ ํ•ด์•ผํ•˜๋ฏ€๋กœ 0~n-1๊นŒ์ง€ ์ฐพ์•„์•ผํ•œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  str2๊ฐœ์˜ ๋ฌธ์ž๊ฐ€ ๊ฐ™๋‹ค๋ฉด
 25     {                                                                                     
 26             i++;
 27     }
 28     if (i == n) //i = n์ด๋ผ๋ฉด ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์ธ 0์„ ๋ฆฌํ„ด (๋น„๊ตํ•œ ๊ฐ’์ด ๋™์ผํ•˜๋ฉด 0๋ฐ˜ํ™˜)
 29         return (0);
 30     return (ptr_s1[i] - ptr_s2[i]); //๊ฐ™์ง€ ์•Š๋‹ค๋ฉด 0์ด ์•„๋‹Œ ๋ฐ˜ํ™˜๊ฐ’ ๋ฆฌํ„ด
 31 }