NULL自动附加在C字符串数组中?

时间:2014-10-18 12:39:03

标签: c macros foreach

我正在尝试用一些c宏实现foreach:

// implement foreach with c macro, tag_c
#include <stdio.h>
#include <stdlib.h>
// foreach implementation for char arrays
#define forchar(iter, array) char* iter; for(iter = array; (*iter) != '\0'; iter++)
// 'foreach' implementation for string arrays, make sure the array ends with NULL
#define forstr(iter, array) char** iter; for(iter = array; *iter; iter++)

int main(int argc, char const* argv[])
{
    char str[] = "what I think is this.";
    forchar(iter, str) {printf("%c ", *iter);}
    printf("\n");
    char *strarray[] = {"Hello, how are you?", "I am fine, thanks. And you?", "I am ok, thanks."};
    forstr(iter1, strarray) {
        printf("%s\n", *iter1);
    }
    return 0;
}

请注意,strarray不以NULL元素结尾,但程序运行良好:

gcc -o bin for2.c && ./bin
w h a t   I   t h i n k   i s   t h i s .
Hello, how are you?
I am fine, thanks. And you?
I am ok, thanks.

0 个答案:

没有答案