Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

finding the size of an string array that saves integers C

I am currently working on a project where I am manipulating command line data, but I can’t seem to get it work if I initialize the size of the array before.

char* len2[50]; // will store "1","2","3" from command line args

int size_arr = sizeof(len2) / sizeof(len2[0]);
printf("%d", size_arr);

this will input 50 when I am looking for it to input 3. How would I be able to find the size?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

int size_arr = sizeof(len2) / sizeof(len2[0]);

sizeof(len2) asks for the total allocated size of len2 in bytes. This only works because C knows how many you allocated at compile time and turns it into a constant. It doesn’t tell you which ones you’ve filled in. C does not keep track of that; you have to.

Because len2 is an array of pointers, you can mark the end with a null pointer. The term for this is a sentinel value. First, be sure to initialize the array to null.

// This will initialize the entire array to NULL
char* len2[50] = {NULL};

Now you can find how many elements are in the array by looking for the first null, or by hitting the allocated size.

size_t len2_size = sizeof(len2) / sizeof(len2[0]);

int size = 0;
for( ; len2[size] != NULL && size < len2_size; size++ );

printf("size: %d\n", size);

This is, incidentally, basically how C strings work. The end of the string is marked with a 0.

Alternatively, you can store the allocated size and number of elements in a struct and keep track, but that’s another question.

Finally, if you’re just reading command line arguments, use argc and argv. argc is the size of argv. argv[0] is the name of the program, and the rest are the command line arguments.

int main( const int argc, const char **argv) {
    printf("%d arguments in argv\n", argc-1);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading