Set value of unsigned char array in C during runtime
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 Posts:
- unsigned char in C with Examples
- size of char datatype and char array in C
- C/C++ program to find the size of int, float, double and char
- Maximum length palindromic substring such that it starts and ends with given char
- Find original array from encrypted array (An array of sums of other elements)
- Find an element in array such that sum of left array is equal to sum of right array
- Minimum cost to reach end of array array when a maximum jump of K index is allowed
- Generate original array from an array that store the counts of greater elements on right
- Maximize the size of array by deleting exactly k sub-arrays to make array prime
- Print modified array after multiple array range increment operations
- Find minimum value to assign all array elements so that array product becomes greater
- Count number of permutation of an Array having no SubArray of size two or more from original Array
- Minimum number greater than the maximum of array which cannot be formed using the numbers in the array
- Sort an array where a subarray of a sorted array is in reverse order
- Check if there exist two elements in an array whose sum is equal to the sum of rest of the array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

