Set value of unsigned char array in C during runtime
Last Updated :
31 Oct, 2019
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:
#include <stdio.h>
#include <string.h>
int main()
{
unsigned char arr[3] = { 0 };
printf ( "Initial unsigned char array:\n" );
for ( size_t i = 0; i < sizeof (arr) / sizeof (arr[0]); i++) {
printf ( "%c " , arr[i]);
}
printf ( "\n" );
memcpy (arr,
(unsigned char []){ '1' , '2' , '3' },
sizeof arr);
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;
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...