私のタスクはstrcpy
次のとおりです。次の制約の下で関数を実装する必要があります。
- 関数に含めることができるステートメントは 7 つまでです。
- できるだけ速くする必要があります。
- 可能な限り最小限のメモリを使用する必要があります。
- my を呼び出す関数では
strcpy
、宛先アドレスは次のように保持されます。char* newDestination = NULL;
- 関数のプロトタイプは次の
strcpy
ようになります。void myStrcp(void** dst, void* src);
uint64_t
各反復を8バイトコピーするために使用するこのソリューションを思いつきました。もしそうなら、私の質問は次のようになります:
- 私よりも優れた解決策はありますか?もしそうなら、なぜそれが優れているのか説明してください?
- プログラムを実行しているOS(
Windows
対Linux
)および/またはプラットフォームは重要ですか?
私の解決策(Windowsの場合):
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <conio.h>
void strCpy(void **dst, void *src);
int main()
{
char *newLocation = NULL;
strCpy((void **)&newLocation, "stringToBeCopied");
printf("after my strcpy dst has the string: %s \n", newLocation);
free(newLocation);
getch();
return 0;
}
void strCpy(void** dst, void* src)
{
// Allocating memory for the dst string
uint64_t i, length = strlen((char *)src), *locDst =
(uint64_t *) malloc(length + 1), *locSrc = (uint64_t *) src;
*dst = locDst;
// Copy 8 Bytes each iteration
for (i = 0; i < length / 8; *locDst++ = *locSrc++, ++i);
// In case the length of the string is not alligned to 8 Bytes - copy the remainder
// (last iteration)
char *char_dst = (char *)locDst, *char_src = (char *)locSrc;
for (; *char_src != '\0'; *char_dst++ = *char_src++);
// NULL terminator
*char_dst = '\0';
}