0

I am having problems related to arrays and their sizes in C. There's something I am doing wrong, but I don't know what exactly.

Here is a sample of the code:

#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(void)
{
    // array of 5 elements
    char array1[] = {'a', 'b', 'c', 'd', 'e'};

    //another array of three elements
    char array2[3] = {'a', 'a', 'a'};

    //size of the second array
    int k = strlen(array2);
    printf("%i\n", k);
}

On running it, I get the size as 8 (which is the sum of the sizes of both arrays). However, this is not supposed to be so. Kindly help me out on what I'm doing (or not doing).

1 Answer 1

2

strlen takes a pointer value, a memory address, and from this memory location counts the bytes until it hits one of value 0 (in this context often called "null terminator"). Since array2 does not contain a byte of zero, what strlen reports depends on how the compiler placed all the variables on stack.

For whatever reason, the stack grows backwards. That means array2 is likely placed before array1, and k right before that one. strlen would count the characters in array2, then the ones in array1, and then find a byte of zero that happened to be there. You could check by printing the first 8 bytes of array2 (which contains only 3).

Even the same compiler with different settings might also align the individual arrays at addresses divisible by 8. In that case, your results might be completely different, likely 3, but it depends on whatever those extra bytes contain (likely 0 for a freshly started programme).

For the size of structures, one would use the sizeof operator, like with a variable int k = sizeof(array2); or with a type int l = sizeof(long);. It returns the number of bytes taken by the variable's type. If your variable is a char[3], it would return 3. If it were an int[6], it would likely report 24. If you want to get the number of elements, that would be sizeof(array2)/sizeof(array2[0]), total size divided by the size of a single element.

Note that this only works for arrays you access by their original names, if you pass them to a function, they are passed as the memory address of their first element, losing the size information.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .