Reputation: 33
In the code below, I would like to have the value of myvar be provided by a program argument.
#include <stdio.h>
int main(int argc, const char **argv)
{
const unsigned char myvar[] = "myvalue";
return 0;
}
How would I get myvar to contain the value of the string from argv[1]?
Upvotes: 0
Views: 1590
Reputation: 223972
An array cannot be initialized by a pointer or by another array. You can only initialize it with an initializer list or (in the char of a char
array) a string constant.
What you can do it copy the contents of another string with strcpy
. And since you'll be using this array as a parameter to an encryption function, it will probably need to be a fixed size.
char myvar[8] = { 0 }; // initialize all values to 0
strncpy(myvar, argv[1], 8); // copy the first 8 bytes
Upvotes: 0
Reputation: 7271
If you are only reading, then you can simply copy the address of argv[1]
like this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char **argv) {
const unsigned char *myvar = NULL;
// Be sure to check argc first
if (argc < 2) {
fprintf(stderr, "Not enough arguments.\n");
return EXIT_FAILURE;
}
myvar = (const unsigned char *)argv[1];
printf("myvar = %s\n", myvar);
}
If you want to change myvar
then you should copy the string with strncpy
or alike.
Upvotes: 3