Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

c - nul terminating a int array

gcc 4.4.4 c89

I was just experimenting with a int array. And something just came to my mind. Can I nul terminate it. For example, I am using a 0 to nul terminate. However, 0 could well be a valid value in this array.

The code below will terminate after the 5. Even though I mean 0 to be a valid number. However, I could specify the size of the array. But in this case, I don't want to this as I am just interested in this particular problem.

Many thanks for any advice,

#include <stdio.h>

static void test(int *p);

int main(void)
{
    int arr[] = {30, 450, 14, 5, 0, 10, ''};

    test(arr);

    return 0;
}

static void test(int *p)
{
    while(*p) {
        printf("Array values [ %d ]
", *p++);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In short, no. Technically nul characters are equally valid in strings too, it's just a convention that we use them for marking the end of a string, and all the standard library functions expect that. There are "double nul-terminated" strings that end in for cases where a string needs to contain a , but then of course you have the problem of not being able to store in the string.

If you don't want to store an array's size separately (or use trickery like sizeof), you need to come up with a sentinel that can be stored in that type but you know won't be part of the array; you could use 45 as long as you're sure arr won't have that as a valid value, it just needs to be unique


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...