NUL终止int数组 [英] nul terminating a int array

查看:130
本文介绍了NUL终止int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC 4.4.4 C89

我只是一个int数组试验。而一些刚来到我的脑海里。我可以NUL终止。例如,我使用的是0到NUL终止。然而,0很可能是这个数组中的有效值。

下code将在5终止后,即使我的意思是0是一个有效的数字。不过,我可以指定数组的大小。但在这种情况下,我不希望这是我在这个特殊的问题只是感兴趣。

非常感谢任何建议,

 的#include<&stdio.h中GT;静态无效测试(INT * P);INT主要(无效)
{
    INT ARR [] = {30,450,14,5,0,10,'\\ 0'};    测试(ARR);    返回0;
}静态无效测试(INT * P)
{
    而(* P){
        的printf(数组值[%D]。\\ n,* P ++);
    }
}


解决方案

在短,没有。技术上NULL字符是字符串同样有效过,它只是我们使用它们标志着字符串的结尾是一个约定,所有的标准库函数预期。有双空终止的字符串,在结束\\ 0 \\ 0 在当一个字符串需要包含例 \\ 0 ,但那么当然你还没有能够存储的问题 \\ 0 \\ 0 的字符串。

如果您不想单独存储数组的大小(或使用诡计像的sizeof ),你需要拿出了可以存储在一个哨兵键入但是你知道会不会是阵列的一部分;你可以使用 45,只要你确定改编不会有,作为一个有效的值,它只是必须是唯一的。

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, '\0'};

    test(arr);

    return 0;
}

static void test(int *p)
{
    while(*p) {
        printf("Array values [ %d ]\n", *p++);
    }
}

解决方案

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 \0\0 for cases where a string needs to contain a \0, but then of course you have the problem of not being able to store \0\0 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

这篇关于NUL终止int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆