我怎么能知道legth数组在C ++中 [英] How can I know legth of array in C++

查看:97
本文介绍了我怎么能知道legth数组在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/1975128/sizeof-an-array-in-the-c-programming-language\">Sizeof在C编程语言中数组?

我有一个字符数组,我想处理它在一个函数,我试过code是这样的:

I have an array of char and I want to process it in a function, I tried code like this:

int main(){
    char *word = new char [5];      
    /*here we make this word
    ....
    */

    process(word);
    puts(word);
}

void process(char *word){
    int sizeOfWord = sizeof(word)-1;
    /* here is cycle that process the word, I need it lenght to know how long cycle must be
    .....
    */
}

但我不能得到阵列与长度的sizeof 。为什么?我怎样才能得到呢?

But I can't get the length of array with sizeof. Why? And how can I get that?

推荐答案

您不能。用指针,就没有办法知道大小

You can't. With a pointer, there is no way to know the size.

你应该做的是,通过的长度,你的过程也。

What you should do is, pass the length of word to your process also.

您应该知道,有数组和指针之间的差异。数组的确是许多元素,因此的sizeof 数组的给它的大小(以字节为单位)。在另一方面指针是只是一个地址。它甚至有可能不会指向数组。因为的sizeof 运营商在编译时计算(除了变长数组),它可以不知道你的意思。

You should know that there is a difference between arrays and pointers. Arrays are indeed a number of elements and therefore sizeof of the array gives its size (in bytes). A pointer on the other hand is just an address. It may not even point to an array. Since the sizeof operator is computed at compile time (except for variable length arrays), it cannot know what you mean.

这个例子想:

void process(char *word);

int main(){
    char *word = new char [5];
    char *word2 = new char [10];

    process(word);
    process(word2);
    /* ... */
}

void process(char *word){
    int sizeOfWord = sizeof(word)-1;  // what should this be?
    /* ... */
}

现在,知道的sizeof 在这种情况下计算在编译的时候,你觉得什么样的价值应该得到什么? 5 10

Now, knowing that sizeof in this case is computed at compile time, what value do you think it should get? 5? 10?

旁注:看起来你正在使用这个数组作为字符串。在这种情况下,您可以轻松获得它的长度与 的strlen

Side note: It looks like you are using this array as a string. In that case, you can easily get its length with strlen.

这篇关于我怎么能知道legth数组在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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