为了磨练我的C技能,我下载了eglibc源代码,我遇到了strncpy.我不明白他为什么要区分n <= 4并进行4次测试的情况.
int
STRNCMP (const char *s1, const char *s2, size_t n)
{
unsigned char c1 = '\0';
unsigned char c2 = '\0';
if (n >= 4)
{
size_t n4 = n >> 2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - c2;
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0' || c1 != c2)
return c1 - …Run Code Online (Sandbox Code Playgroud) 我正在线上学习操作系统课程,我完成了第一个课程http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-828-operating-system-engineering-fall- 2012/assignments/MIT6_828F12_assignment1.pdf
但让我感到惊讶的是他们如何返回数据结构,他们使用数据结构并返回一个较小的数据结构,并使用它们只是将其转换回来.我看到它可以优化代码,但这样安全吗?这是好习惯吗?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct small
{
int n ;
};
struct big
{
int n ;
char * string ;
};
struct small* f()
{
struct big* x = malloc(sizeof(struct big));
x->n = 'X';
x->string = strdup("Nasty!");
return (struct small*) x ;
}
int main(int argc, char *argv[])
{
struct big *y = (struct big*)f();
printf("%s\n",y->string);
}
Run Code Online (Sandbox Code Playgroud)
编辑1:这是来自mit的链接,我只是在我自己的代码中复制了这个想法. http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-828-operating-system-engineering-fall-2012/assignments/sh.c