实现在C字符串拷贝功能 [英] Implementing a string copy function in C

查看:273
本文介绍了实现在C字符串拷贝功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近的一次面试时,有人问我实现我自己的字符串拷贝功能。我设法写code,我认为作品的程度。然而,当我回到家里再次尝试这个问题,我意识到这是一个复杂得多比我想象。这里是我想出了code:

At a recent job interview, I was asked to implement my own string copy function. I managed to write code that I believe works to an extent. However, when I returned home to try the problem again, I realized that it was a lot more complex than I had thought. Here is the code I came up with:

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

char * mycpy(char * d, char * s);

int main() {

  int i;
  char buffer[1];

  mycpy(buffer, "hello world\n");
  printf("%s", buffer);

  return 0;
}

char * mycpy (char * destination, char * source) {

  if (!destination || !source) return NULL;

  char * tmp = destination;

  while (*destination != NULL || *source != NULL) {
    *destination = *source;
    destination++;
    source++;
  }

  return tmp;
}

我看了一些其他的例子,并在网上发现,由于在C中的所有字符串都是空终止,我已读了空字符,然后附加一个空字符到目标字符串飞去。

I looked at some other examples online and found that since all strings in C are null-terminated, I should have read up to the null character and then appended a null character to the destination string before exiting.

不过有一件事我很好奇的是记忆是如何被处理的。我发现,如果我用的strcpy()库函数,我可以10个字符的字符串拷贝到尺寸1的字符数组这怎么可能?是的strcpy()函数不知何故分配更多的内存到目的地?

However one thing I'm curious about is how memory is being handled. I noticed if I used the strcpy() library function, I could copy a string of 10 characters into a char array of size 1. How is this possible? Is the strcpy() function somehow allocating more memory to the destination?

推荐答案

好面试问题有好几层,哪个候选可以显示不同层次的理解。

Good interview question has several layers, to which to candidate can demonstrate different levels of understanding.

在句法C语言层,下面的code是从经典的Kernighan和Ritchie的书(C程序设计语言):

On the syntactic 'C language' layer, the following code is from the classic Kernighan and Ritchie book ('The C programming language'):

while( *dest++ = *src++ )
    ;

在接受记者采访时,你确实可以指出的功能是不是安全,最显着的 * DEST 缓冲区不够大。此外,还有可能是重叠的,也就是说,如果 DEST 指向的src 缓冲的中间,你就会有无穷的循环(这将最终导致内存访问故障)。

In an interview, you could indeed point out the function isn't safe, most notably the buffer on *dest isn't large enough. Also, there may be overlap, i.e. if dest points to the middle of the src buffer, you'll have endless loop (which will eventually creates memory access fault).

这篇关于实现在C字符串拷贝功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆