Q：函数总是返回0 [关闭]

Function:

``````int num(char a[]) //将字符串型的数字转化成int
{
int  z, x, y;
z = 0;
int m = sizeof(a);

if(m == 1)
z = a[0] - 48;

if(m == 2)
{
x = a[0] - 48;
y = a[1] - 48;
z = x * 10 + y;
}

if(m == 3)
{
x = a[0] - 48;
y = a[1] - 48;
z = a[2] - 48;
z = x * 100 + y * 10 + z;
}
``````

eg: `char a[3]={2,15};`, but `num(a) = 0`.
I don't know why.

``````int num(char a[]) //将字符串型的数字转化成int
{
int  z, x, y;
z = 0;
int m = sizeof(a);

if(m == 1)
z = a[0] - 48;

if(m == 2)
{
x = a[0] - 48;
y = a[1] - 48;
z = x * 10 + y;
}

if(m == 3)
{
x = a[0] - 48;
y = a[1] - 48;
z = a[2] - 48;
z = x * 100 + y * 10 + z;
}
``````

eg: `char a[3]={2,15};`, but `num(a) = 0`.
I don't know why.

answer1： 回答1：

The parameter of the function declared like char a[] is adjusted to type char *. The size of the pointer does not depend on how many elements the array passed as an argument has.

The valid function can look the following way

``````#include <cstring>

//...

int num( const char a[] )//将字符串型的数字转化成int
{
int  z,x,y;

size_t n = std::strlen( a );

z = 0;

if( n == 1 )
z = a[0] - '0';

if ( n == 2 )
{
x = a[0] - '0';
y = a[1] - '0';
z = x * 10 + y;
}

if ( n == 3 )
{
x = a[0] - '0';
y = a[1] - '0';
z = a[2] - '0';
z = x * 100 + y * 10 + z;
}
//...
``````

If you need simply to form a number from a character array you could use standard C function atoi. Or you could write a loop

``````z = 0;

for ( size_t i = 0; i < 3 && a[i]; i++ ) z = 10 * z + a[i] - '0';
``````

Take into account that if it is the all that the function has to do then you shall include return statement

``````return z;
``````

``````#include <cstring>

//...

int num( const char a[] )//将字符串型的数字转化成int
{
int  z,x,y;

size_t n = std::strlen( a );

z = 0;

if( n == 1 )
z = a[0] - '0';

if ( n == 2 )
{
x = a[0] - '0';
y = a[1] - '0';
z = x * 10 + y;
}

if ( n == 3 )
{
x = a[0] - '0';
y = a[1] - '0';
z = a[2] - '0';
z = x * 100 + y * 10 + z;
}
//...
``````

``````z = 0;

for ( size_t i = 0; i < 3 && a[i]; i++ ) z = 10 * z + a[i] - '0';
``````

``````return z;
``````
c++