How to find char * "array length in C?

I declare the following array:

char* array [2] = { "One", "Two"};

I pass this array to a function. How to find the length of this array in a function?

+5
source share
6 answers

You cannot find the length of the array after you pass it to the function without extra effort. You will need:

  • Use the container in which the size is stored, for example vector( recommended ).
  • Pass the size along with it. This will probably require a minimal change to your existing code and will be the fastest solution.
  • , , C do 1. , , , , . .
  • templating . : ?

1 , , , C- .

+17

.

std::vector < std::string >

,

:

template <typename T, size_t N>
void YourFunction( T (&array)[N] )
{
    size_t myarraysize = N;
}
+7

C .

void foo(int array[]) {
    /* ... */
}

void bar(int *array) {
    /* ... */
}

:

6.3.2.1.3: , sizeof , , , , '' '' lvalue. , undefined.

, foo() bar(), , :

int a[10];
int b[10];
int c;

foo(a);
foo(&b[1]);
foo(&c);

: void foo(int *array) , , . : void foo(int array[]), , .

, , , , :

  • . ( int main(int argc, char *argv)).
  • , NULL, . ( char *s="almost a string"; execve(2).)
  • , . (Think printf("%s%i", "hello", 10); - . printf(3) stdarg(3), .)
+2

, togather.

int n=2;
int size=0;
char* array [n] = { "One", "Two"};

for (int i=0;i<n;++i)
  size += strlen(array[i];

:

, , , . -

, , , , .

char* array [] = { (char*)2,"One", "Two"};

long size=(long)array[0];
for(int i=1; i<= size;++i)
  printf("%s",array[i]);

NULL

char * array [] = { "", "", (char *) 0};

for(int i=0;array[i]!=0;++i)
{
  printf("%s",array[i]);
}
0

. NULL-. , NULL, , , NULL...

0

All Articles