Created
September 6, 2014 08:35
-
-
Save karupanerura/9454a2a000de56e9352e to your computer and use it in GitHub Desktop.
Goのスライスの挙動を理解するためにCでそれっぽいやつを再実装してみる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> // size_t | |
struct IntSlice { | |
int *ptr; | |
size_t len; | |
size_t cap; | |
}; | |
struct IntSlice newIntSlice (int *ptr, size_t start, size_t end, size_t cap) { | |
size_t len = end - start; | |
struct IntSlice s = { ptr + start, len, cap }; | |
return s; | |
} | |
struct IntSlice newIntSliceFromSlice (struct IntSlice slice, size_t start, size_t end) { | |
size_t len = end - start; | |
size_t ncap = slice.cap - start; | |
struct IntSlice s = { slice.ptr + start, len, ncap }; | |
return s; | |
} | |
void dumpSlice (struct IntSlice slice) { | |
printf("ptr:%p len:%d, cap:%d\t", slice.ptr, (int)slice.len, (int)slice.cap); | |
for (int i = 0; i < slice.len; i++) { | |
printf("%d ", slice.ptr[i]); | |
} | |
fputc('\n', stdout); | |
} | |
int main (void) { | |
int a[5] = {1, 2, 3, 4, 5}; | |
struct IntSlice as1 = newIntSlice(a, 0, 5, 5); | |
dumpSlice(as1); | |
struct IntSlice as2 = newIntSliceFromSlice(as1, 0, 0); | |
dumpSlice(as2); | |
struct IntSlice as3 = newIntSliceFromSlice(as2, 0, 2); | |
dumpSlice(as3); | |
struct IntSlice as4 = newIntSliceFromSlice(as3, 2, 5); | |
dumpSlice(as4); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment