How Do You Create a Char Array with Other Variables?

◀ Advanced▶ A List of Traps and Tips
Amazon If you use C, a need may arise where you want to create a global char array from other variables. The following is sample code showing how you normally create a global string variables:
char fileName[]="D:\\image\\original.bmp";
char fileNameFace[]="D:\\image\\face.bmp";

void someFunction(){
..
// use fileName
..
// use fileNameFace
..
}

As you can see, someFunction can use fileName and fileNameFace because fileName and fileNameFace are global variables.


However, suppose you want to change the folder from image to anotherImageFolder, you will need to manually change the value of fileName and that of fileNameFace. While doing so may not be much of a hassle, consider the case where you have 10 such strings. Changing 10 string variables can be a hassle.

So question is: How can you extract the folder name and make it a variable? If you can do that, you will only need to change the value of one variable instead of 10.


Declare a macro

#define createString(s1, s2, s3) sprintf(s1, "D:\\%s\\%s.bmp", s2, s3);

This macro allows you to construct a string, aka a char array, from two other strings.


Declare the strings you need


In my example, I need the following strings. Declare them at the top of your source code below the macro. Declare more if you need more.
char imageDir[]="image";
char fileName[1024];
char fileNameFace[1024];

The char array variable imageDir is for you to put the name of the image folder.


Create strings in the beginning of main()


In the beginning of your main() function, write the following code:
createString(fileName, imageDir, "original");
createString(fileNameFace, imageDir, "face");

That's it! Next time suppose you want to change the folder from image to bigImage, simply manually change the following line of code:


char imageDir[]="image";


to

char imageDir[]="bigImage";


And recompile and run the program and fileName, fileNameFace, and all other variables you may have declared will be updated with the new folder automatically. One manual change is all you need to update all the related char array variables. How nice!
◀ Advanced▶ A List of Traps and Tips

fShare
Questions? Let me know!