This article explains how to set or change the value of unsigned char array during runtime in C.
Given:
Suppose we have an unsigned char array of size n
unsigned char arr[n] = {}; // currently arr = {'', '', '', ...}
To do:
We want to set or change the values of this array during runtime.
For example, we want to make the array
arr = {'1', '2', '3', ...}
Solution:
This can be achieved with the help of memcpy() method. memcpy() is used to copy a block of memory from a location to another. It is declared in string.h
Syntax:
// Copies "numBytes" bytes from address "from" to address "to" void * memcpy(void *to, const void *from, size_t numBytes);
Below is the implementation of the above program:
// C program to set the value // of unsigned char array during runtime #include <stdio.h> #include <string.h> int main()
{ // Initial unsigned char array
unsigned char arr[3] = { 0 };
// Print the initial array
printf ( "Initial unsigned char array:\n" );
for ( size_t i = 0; i < sizeof (arr) / sizeof (arr[0]); i++) {
printf ( "%c " , arr[i]);
}
printf ( "\n" );
// Using memcpy() to change the values
// during runtime
memcpy (arr,
(unsigned char []){ '1' , '2' , '3' },
sizeof arr);
// Print the updated array
printf ( "Updated unsigned char array:\n" );
for ( size_t i = 0; i < sizeof (arr) / sizeof (arr[0]); i++) {
printf ( "%c " , arr[i]);
}
printf ( "\n" );
return 0;
} |
Recommended Articles