I've a string array:
char array[128][128];
To add strings in this array, I read a file, and append a line if "192.168.101.2"
is contained in that line:
while ((read = getline(&line, &len, fp)) != -1) {
if (strstr(line, "192.168.101.2") != NULL) {
printf("%s\n", line);
strcpy(array[i], line);
i ;
}
}
Now, I would like to know how many strings this array contains. I've tried:
sizeof(array)/sizeof(array[0])
, but it always returns 128. How can I achieve this?
And, how can i pass an array of strings to a function? I've tried:
void array_length(char array[int][int]);
but:
main.c:15:31: error: expected expression before ‘int’
15 | void array_length(char array [int][int]);
CodePudding user response:
How to know how many strings does a string array contain?
C does not really have arrays, as they are in most other languages. Sure, you have array types, and can initialize arrays directly. But at runtime, array is just a pointer. There is no additional runtime information about it.
So, you have to keep track of both array maximum size and how many (or which) elements of array are used/initialized yourself.
So, here's code:
// char *array[128] might be better, but would require use of malloc for every string
char array[128][128];
// array size in bytes / one row size in bytes = number of rows
const size_t array_capacity = sizeof (array) / sizeof(array[0]);
// update len as you add strings of text
size_t array_len = 0;
CodePudding user response:
int length=0;
while(array[length ][0]!='\0');
printf("%d",length); // in c/c