3 回答
TA贡献1785条经验 获得超4个赞
T
T
sizeof
&
void foo(char *a, size_t asize){ // do something with a}int bar(void){ char str[6] = "Hello"; foo(str, sizeof str);}
foo
str
char [6]
char *
foo
char *a
char a[6]
sizeof str
sizeof
void returnArray(const char *srcArray, size_t srcSize, char *dstArray, char dstSize){ ... dstArray[i] = some_value_derived_from(srcArray[i]); ...}int main(void){ char src[] = "This is a test"; char dst[sizeof src]; ... returnArray(src, sizeof src, dst, sizeof dst); ...}
char *returnArray(const char *srcArray, size_t srcSize, size_t *dstSize){ char *dstArray = malloc(srcSize); if (dstArray) { *dstSize = srcSize; ... } return dstArray;}int main(void){ char src[] = "This is a test"; char *dst; size_t dstSize; dst = returnArray(src, sizeof src, &dstSize); ... free(dst); ...}
free
dst
char
char
[]
src[i]
dst[i]
i
src
T
char (*returnArray(const char *srcArr, size_t srcSize))[SOME_SIZE]{ char (*dstArr)[SOME_SIZE] = malloc(sizeof *dstArr); if (dstArr) { ... (*dstArr)[i] = ...; ... } return dstArr;}int main(void){ char src[] = "This is a test"; char (*dst)[SOME_SIZE]; ... dst = returnArray(src, sizeof src); ... printf("%c", (*dst)[j]); ...}
SOME_SIZE
TA贡献1865条经验 获得超7个赞
数组h
#define IMPORT_ARRAY(TYPE) \ \struct TYPE##Array { \ TYPE* contents; \ size_t size; \}; \ \struct TYPE##Array new_##TYPE##Array() { \ struct TYPE##Array a; \ a.contents = NULL; \ a.size = 0; \ return a; \} \ \void array_add(struct TYPE##Array* o, TYPE value) { \ TYPE* a = malloc((o->size + 1) * sizeof(TYPE)); \ TYPE i; \ for(i = 0; i < o->size; ++i) { \ a[i] = o->contents[i]; \ } \ ++(o->size); \ a[o->size - 1] = value; \ free(o->contents); \ o->contents = a; \} \void array_destroy(struct TYPE##Array* o) { \ free(o->contents); \} \ TYPE* array_begin(struct TYPE##Array* o) { \ return o->contents; \} \ TYPE* array_end(struct TYPE##Array* o) { \ return o->contents + o->size; \}
主.c
#include <stdlib.h>#include "array.h"IMPORT_ARRAY(int);struct intArray return_an_array() { struct intArray a; a = new_intArray(); array_add(&a, 1); array_add(&a, 2); array_add(&a, 3); return a;}int main() { struct intArray a; int* it; int* begin; int* end; a = return_an_array(); begin = array_begin(&a); end = array_end(&a); for(it = begin; it != end; ++it) { printf("%d ", *it); } array_destroy(&a); getchar(); return 0;}
- 3 回答
- 0 关注
- 658 浏览
添加回答
举报