0

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]);
4
  • 3
    When the loop ends, the value of i will have the number of strings in the array. Save it and use it. Commented Sep 15, 2022 at 9:25
  • 1
    And please, one question per question. But quite honestly, how to pass arrays of arrays should be taught by any decent book, tutorial or class. Commented Sep 15, 2022 at 9:26
  • I know, but how can I calculate the number of strings without the i index? Commented Sep 15, 2022 at 9:27
  • 2
    Why would you want to do it without i? You must have that index to store into the correct element of your array. If you really want to do it without a counter you can add a sentinel, i.e. an array element that is defined to be invalid. For strings that could be an empty string after the last string read from your file. Commented Sep 15, 2022 at 9:32

1 Answer 1

4

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; 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.