Reputation: 884
I need to pass a char variable to the next value in an array in C.
I am declaring the array (list) and the size (0), I then have the variable I want to insert into the next element in the array, which is value.
char list[100];
size_t size = 0;
char *value = "name";
I then want to insert the value into the next element in the array, but this does not work:
list[size++] = "%s",value;
This only works for a single character, e.g:
list[size++] = 'n';
list[size++] = 'a'
list[size++] = 'm'
list[size++] = 'e'
Upvotes: 0
Views: 115
Reputation: 310960
There are several approaches how this can be done. Also the correct approach depends on whether you want to srore in list a string terminated with zero or the terminating zero has not be included in list.
If you want to include the terminating zero then you can initially define list as having string literal "name".
For example
char list[100] = "name";
size_t size = strlen( list );
If you want to place the string literal in list after its definition you can use either standard function strcpy
or strcat
For example
char list[100];
size_t size = 0;
char *value = "name";
//...
strcpy( list + size, value );
size += strlen( value );
Or
char list[100];
size_t size = 0;
char *value = "name";
//...
list[size] = '\0' // if list already has the terminating zero you may remoce this statement
strcat( list, value );
size += strlen( value );
If you do not want to store the terminating zero then you should use function memcpy
For example
char list[100];
size_t size = 0;
char *value = "name";
//...
size_t n = strlen( value );
memcpy( list + size, value, n );
size += n;
And at last you can use a loop. For example
char list[100];
size_t size = 0;
char *value = "name";
//...
char *p = value;
while ( list[size++] = *p++ );
Upvotes: 1
Reputation: 1051
String assignment is not supported by C. You should use function like strcpy
or strcat
.
To copy your string value
to your list
at a given offset size
, you can do:
strcpy(list + size, value);
The content of your variable value
will be copied at the size
th position in your list
array.
For more information, please check man strcpy
, man strncpy
, man strcat
and man strncat
.
Upvotes: 1
Reputation: 19864
char value = "name";
This is wrong. Either value
should be a pointer or a char array to hold the string.
char *value = "name";
char value[20] = "name";
char list[100];
This is a char array which can hold 100 characters and you need to add each character individually by using a loop or use strcpy()
to copy.
Upvotes: 1
Reputation: 4041
It will not work.
char value="name";
Change that into like this.
char value[]="name";
Reason you are not able assign value[size] is stores only single character not a whole string. It having the size of 255 only. You can use this one.
strcpy(list,"value");
Upvotes: 1