I've declared:
char array_slave_1[128][128];
int array_length(char *a[]){
int i = 0;
while(a[i] != NULL){
i ;
}
return i;
}
int x = array_length(array_slave_1);
I obtain:
main.c:101:26: warning: passing argument 1 of ‘array_length’ from incompatible pointer type [-Wincompatible-pointer-types]
101 | int x = array_length(array_slave_1);
| ^~~~~~~~~~~~~
| |
| char (*)[128]
main.c:16:24: note: expected ‘char **’ but argument is of type ‘char (*)[128]’
16 | int array_length(char *a[]){
I'm not sure if it is correct the way of passing the argument to the function I declared...I think the the problem is this one, but I don't know how to correctly implement the function array_lenght.
CodePudding user response:
char array_slave_1[128][128]
This is 2-dimensional array of char as paramter:
int array_length(char *a[])
This is array of pointers to char (which might be C strings, but could be other char/byte buffers, or single chars too). Except because it is a function parameter, it really is pointer to pointer, so if you are a novice you'd be better off writing what it really is, to avoid getting confused:
int array_length(char **a)
Types of array_slave_1
and a
are fundamentally different, and incompatible.
If you want to make your function take the array as parameter, you could do:
int array_length(char a[128][])
which is same as this (note the extra ()
compared to code in question, they matter!), because array parameters really are pointers, so you have a pointer to one or more char[128]
buffers:
int array_length(char (*a)[128])
Then you need a different way to determine the array length, though. Perhaps empty string means end of strings? That's up to you, really.
Alternative is to change your array to be array of pointers:
char *array_slave_1[128]; // 128 pointers to char buffer or C string
// remember that you must allocate the space of each string!
CodePudding user response:
Perhaps you are just "over complicating" things.
Here is a "best guess" at what you might be trying to achieve (based on allocating room for 128x strings, each up to 127 bytes (plus a null terminator.)
#include <stdio.h>
#include <string.h>
int main() {
char array_slave_1[ 128 ][ 127 1 ]; // notation helps signify this is a string
strcpy( array_slave_1[ 0 ], "Hello World!" );
strcpy( array_slave_1[ 1 ], "Foobar" );
for( int i = 0; i < 2; i )
printf( "'%s' length %d\n", array_slave_1[ i ], strlen( array_slave_1[ i ] ) );
return 0;
}
Output
'Hello World!' length 12
'Foobar' length 6
strlen()
has already been done in the standard C library.