Copying and initializing using mem* functions#
Copying#
Activity 51 (Copying using mem*)
In section Copying an array for passing-by-value we copied an array using a
forloop. Which character array manipulation (mem*) function could be useful?Convert the following code.
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#define WIDTH 5
typedef enum { EMPTY, SENTENCE, PHOTO, BOTH } collage_t[WIDTH];
collage_t collage;
/**
* Wants only to write something on the first empty slot
*/
void sentence_friend(collage_t collage) {
for (size_t col = 0; col < WIDTH; ++col)
if (collage[col] == EMPTY) {
collage[col] = SENTENCE;
return;
}
}
/**
* picks a random place and puts both a sentence and a photo.
*/
void creative_friend(collage_t collage) {
for (size_t tries = 0; tries < WIDTH; ++tries) {
size_t col = rand() % WIDTH;
if (collage[col] == EMPTY) {
collage[col] = BOTH;
return;
}
}
}
/**
* Careless friend just overwrites
*/
void careless_friend(collage_t collage) { collage[rand() % WIDTH] = PHOTO; }
int main() {
// FOR DEMO: use debugger to visualize the changes
sentence_friend(collage);
creative_friend(collage);
// You copy the collage for the careless friend
collage_t collage_copy;
for (size_t col = 0; col < WIDTH; ++col)
collage_copy[col] = collage[col];
careless_friend(collage_copy);
// Then you merge the collage_copy into the collage.
}
Initializing#
Activity 52 (Initializing using mem*)
Imagine you want to give an empty collage to another friend, but you want to reuse
collage_copy. Whichmem*function would you use.Add it to the code above and test its effect using the debugger.