How to resolve the algorithm Array length step by step in the C programming language
Published on 7 June 2024 03:52 AM
How to resolve the algorithm Array length step by step in the C programming language
Table of Contents
Problem Statement
Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Array length step by step in the C programming language
1st Source Code
- This C code snippet initializes a constant array of strings called
fruit
and calculates its length using thesizeof
operator and division: - It prints the length of the array, which is 2 in this case, representing the number of elements in the array.
2nd Source Code
- This C code snippet defines a macro
ARRAY_LENGTH
to calculate the length of an array by dividing its size by the size of its first element: - It uses the
#define
directive to create a preprocessor macro that takes an array name as a single argument. - The macro calculates the length of the array by dividing the size of the array (obtained using
sizeof(A)
) by the size of its first element (obtained usingsizeof(A[0])
).
3rd Source Code
- This C code snippet defines a
StringArray
structure that represents a dynamic array to hold strings: - It includes memory management functions to create, add elements to, and delete the
StringArray
instance. - It allocates memory for the array of strings and its individual elements, allowing for flexible storage and dynamic growth of the array.
- A
main
function demonstrates the usage of theStringArray
by dynamically adding elements, printing the array's contents, and then freeing the allocated memory.
4th Source Code
- This C code snippet explores the different ways of using, defining, and allocating fixed-size arrays in C:
- It defines global and local arrays of various types (const, static, and non-const) to illustrate how their sizes are determined at compile time.
- It also includes examples of memory blocks allocated dynamically and how to calculate their lengths.
- The code performs tests and prints results to compare the sizes and lengths of arrays declared in various forms.
- This helps clarify how to work with fixed-size arrays and memory allocation in C programming.
Source code in the c programming language
#include <stdio.h>
int main()
{
const char *fruit[2] = { "apples", "oranges" };
// Acquire the length of the array by dividing the size of all elements (found
// with sizeof(fruit)) by the size of the first element.
// Note that since the array elements are pointers to null-terminated character
// arrays, the size of the first element is actually the size of the pointer
// type - not the length of the string.
// This size, regardless of the type being pointed to, is 8 bytes, 4 bytes, or
// 2 bytes on 64-bit, 32-bit, or 16-bit platforms respectively.
int length = sizeof(fruit) / sizeof(fruit[0]);
printf("%d\n", length);
return 0;
}
#define ARRAY_LENGTH(A) (sizeof(A) / sizeof(A[0]))
#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
struct StringArray
{
size_t sizeOfArray;
size_t numberOfElements;
char** elements;
};
typedef struct StringArray* StringArray;
StringArray StringArray_new(size_t size)
{
StringArray this = calloc(1, sizeof(struct StringArray));
if (this)
{
this->elements = calloc(size, sizeof(int));
if (this->elements)
this->sizeOfArray = size;
else
{
free(this);
this = NULL;
}
}
return this;
}
void StringArray_delete(StringArray* ptr_to_this)
{
assert(ptr_to_this != NULL);
StringArray this = (*ptr_to_this);
if (this)
{
for (size_t i = 0; i < this->sizeOfArray; i++)
free(this->elements[i]);
free(this->elements);
free(this);
this = NULL;
}
}
void StringArray_add(StringArray this, ...)
{
char* s;
va_list args;
va_start(args, this);
while (this->numberOfElements < this->sizeOfArray && (s = va_arg(args, char*)))
this->elements[this->numberOfElements++] = strdup(s);
va_end(args);
}
int main(int argc, char* argv[])
{
StringArray a = StringArray_new(10);
StringArray_add(a, "apple", "orange", NULL);
printf(
"There are %d elements in an array with a capacity of %d elements:\n\n",
a->numberOfElements, a->sizeOfArray);
for (size_t i = 0; i < a->numberOfElements; i++)
printf(" the element %d is the string \"%s\"\n", i, a->elements[i]);
StringArray_delete(&a);
return EXIT_SUCCESS;
}
#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
// Fixed size global arrays
static const int scGlobal[N];
const int cGlobal[N];
static int sGlobal[N];
int Global[N];
#define TEST(A, N) \
do { \
puts(""); \
printf("directly called: sizeof(%8s) = %2d, length = %2d, %s\n",\
#A, \
sizeof(A), \
sizeof(A) / sizeof(int), \
sizeof(A) / sizeof(int) == N ? "pass" : "fail"); \
\
test1(#A, A, N); \
test2(#A, A, N); \
test3(#A, A, N); \
} while (0);
void test1(char* name, int* A, int n)
{
printf("as parameter int* A: sizeof(%8s) = %2d, length = %2d, %s\n",
name,
sizeof(A),
sizeof(A) / sizeof(int),
sizeof(A) / sizeof(int) == n ? "pass" : "fail");
}
void test2(char* name, int A[], int n)
{
printf("as parameter int A[]: sizeof(%8s) = %2d, length = %2d, %s\n",
name,
sizeof(A),
sizeof(A) / sizeof(int),
sizeof(A) / sizeof(int) == n ? "pass" : "fail");
}
void test3(char* name, int A[10], int n)
{
printf("as parameter int A[10]: sizeof(%8s) = %2d, length = %2d, %s\n",
name,
sizeof(A),
sizeof(A) / sizeof(int),
sizeof(A) / sizeof(int) == n ? "pass" : "fail");
}
int main(int argc, char argv[])
{
// Fixed size local arrays (defined inside curly braces block)
static const int scLocal[N];
const int cLocal[N];
static int sLocal[N];
auto int aLocal[N];
int Local[N];
// Fixed size VLA arrays can/should be used instead dynamically alocated
// blocks. VLA has not implemented in Microsoft Visual Studio C.
srand(time(NULL));
int n = N + rand() % 2; // the value of n is unknow in the compile time?
#ifndef _MSC_VER
int vlaLocal[n];
#endif
// Memory blocks as ersatz arrays. This is not all possible ways to allocate
// memory. There are other functions, like LocalAlloc, HeapAlloc, sbreak...
// Don't use alloca in any serious program - this function is really bad
// choice - it can corrupt the program stack and generate a stack overflow.
int* mBlock = (int*)malloc(n * sizeof(int));
int* cBlock = (int*)calloc(n, sizeof(int));
int* aBlock = (int*)_alloca(n * sizeof(int)); // don't use in your programs!
TEST(scGlobal, N);
TEST(cGlobal, N);
TEST(sGlobal, N);
TEST(Global, N);
TEST(scLocal, N);
TEST(cLocal, N);
TEST(sLocal, N);
TEST(aLocal, N);
TEST(Local, N);
#ifndef _MSC_VER
TEST(vlaLocal, n);
#endif
TEST(mBlock, N);
TEST(cBlock, N);
TEST(aBlock, N);
free(mBlock, N);
free(cBlock, N);
// free must not be called on aBlock
return 0;
}
You may also check:How to resolve the algorithm Split a character string based on change of character step by step in the 8086 Assembly programming language
You may also check:How to resolve the algorithm Sort using a custom comparator step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Loops/Infinite step by step in the Jsish programming language
You may also check:How to resolve the algorithm Stack step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Empty program step by step in the Racket programming language