strlen()是否适用于int数组? [英] Would strlen() work for int array?

查看:1514
本文介绍了strlen()是否适用于int数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include   <   stdio.h  >  
void main()
{
int b [ 100 < /跨度>];
int a = 10 ;
执行
{
b [i] = a%2;
c = a / 2;
a = c;
} while (a> = 2

len = strlen的(b)中;
printf( %d,b [i]);
getch();
}



len无法正常工作。当变量'a'初始化为更大的数字时,len的输出为4.当在printf()中给出b [100]代替b [i]时,答案是6.如何得到长度为正确排列变量'a'的任何值。请帮我。谢谢。

解决方案

文档始终是第一个调用点。 strlen()用于字符串就是你需要知道的。 http://www.cplusplus.com/reference/cstring/strlen/ [ ^ ]



获得数组成员数量(与字节数不同)的方法是:



  int  b [ 100 ]; 
int len = sizeof (b)/ sizeof(b [ 0 ]);





http://www.c4learn.com/c-programming/sizeof-operator/ [ ^ ]


strlen对整数的效果不好,只是因为存储整数的方式。

假设32位整数,它们占用4个字节(16位整数将使用2个字节),而对于Windows PC,它们以小端格式存储 - 整数值的最低有效字节将占用最低地址。

strlen在到达包含'\0'的字节时停止计算字符串的大小 - 所以如果你的第一个整数值小于256,它会在它找到第二个字节时停止,并返回长度为1.

数字越大,计数越长:如果你有16位整数,你的数组包含256,255,1777那么它所看到的第三个字节将是零,它将假设这是字符串的结尾。



你必须手动进行搜索,除非pwasser的解决方案是你正在寻找的。


答案是否定的。

strlen()是一个字符串函数,你不能将它用于其他任何东西。 ;)

#include<stdio.h>
void main()
{ 
  int b[100];
  int a=10;
  do
  {
    b[i]=a%2;
    c=a/2;
    a=c;
  } while(a>=2)

  len=strlen(b);
  printf("%d",b[i]);
  getch();
}


The len doesn't work properly. When variable 'a' is initialized a greater number, the output for len is 4. When b[100] is given in place of b[i] in printf(), the answer is 6. How can I get the length of the array correctly for any value of variable 'a'. Please help me. Thanks.

解决方案

The documentation is always the first point of call. strlen() is for strings is all you need to know. http://www.cplusplus.com/reference/cstring/strlen/[^]

The way to get the number of members (as distinct from the number of bytes) of your array is this:

int b[100];
int len=sizeof(b)/sizeof(b[0]);



http://www.c4learn.com/c-programming/sizeof-operator/[^]


strlen wouldn't work too well for integers, simply because of the way integers are stored.
Assuming 32bit ints, they take four bytes (16 bit integers will use 2 bytes) and for Windows PC's they stored in little endian format - the least significant byte of the integer value will occupy the lowest address.
strlen stops counting the size of a string when it reaches a byte containing '\0' - so if your first integer value is less than 256 it will stop when it spots the second byte, and return a length of 1.
The bigger the numbers, the longer the count will go: if you have 16 bit integers, and your array contains 256, 255, 1777 then the third byte it looks at will be zero, and it will assume that is the end of the string.

You will have to do the search manually, unless pwasser's solution is what you are looking for.


The answer is no.
strlen() is a string function and you can't use it for anything else. ;)


这篇关于strlen()是否适用于int数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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