[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 910
  • Last Modified:

sizeof array....

can someone pls help me how to figure out the size of the _environ array?

printf("%d", sizeof(*_environ)/sizeof(_environ[0]));

...this obviously doesn't work.... why?
0
sa9813
Asked:
sa9813
1 Solution
 
wyllikerCommented:
The _environ[] array is not a fixed length array. It can change if your program adds an environment string, for example.  In that case it's address may even change in memory.  It is also an array of pointers to character strings.


So if you do something like ...


unsigned short EnvCnt = 0;

while(_environ[EnvCnt])
    ++EnvCnt;

You can know how many environment variables there are.


If you want to know the size of all of the strings then you would do something like ...


unsigned short EnvCnt = 0;
// Not including NULL Terminators
unsigned short EnvTotalStringSize = 0;
// including NULL terminators
unsigned short EnvTotalSize = 0;

while(_environ[EnvCnt])
{
    EnvTotalString += strlen(_environ[EnvCnt]);
    EnvTotalSize += strlen(_environ[EnvCnt])+1;
    ++EnvCnt;
}

// Environment ends with TWO (2) NULL terminators
EnvTotalSize += 2;






0
 
rbrCommented:
It depends on how this array was created.

int array[1000];

printf ("%d",sizeof(array)/sizeof(array[0]));
will print 1000

int *array;

array = calloc (1000,sizeof(int));
printf ("%d",sizeof(array)/sizeof(array[0]));
will print the wrong result.
0
 
mohitdasCommented:
The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t.

When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated arrays or external arrays.

int  array[] = { 1, 2, 3, 4, 5 };
size_t  sizearr = sizeof( array ) / sizeof( array[0] );

above will give the number of elements in the array.

sizeof(*_environ)/sizeof(_environ[0])
as this refers to some external array, it'll definitely not work.  :)
Mohit.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now