Reputation: 113
I am looking to modify a char array with different strings, like a temp char array which takes various strings. Let's say a char array A[10] = "alice", how to assign A[10] = "12". Without using string functions?
TIA
Upvotes: 0
Views: 769
Reputation: 1359
it's like Govind Parmar's answer but with for loop.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[11] = "hello world";
char new[5] = "2018";
int i = 0;
for (i; new[i] != '\0'; i++)
str[i] = new[i];
str[i] = '\0';
printf("str => '%s' ",str);
return 0;
}
output :
str => '2018'
Upvotes: 2
Reputation: 339
Well since string array is noting but pointer to array you can simply assign like this
int main(void) {
char *name[] = { "Illegal month",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
name[10] = "newstring";
printf("%s",name[10]);
return 0;
}
Upvotes: 0
Reputation: 21532
In C, a string is just an array of type char
that contains printable characters followed by a terminating null character ('\0'
).
With this knowledge, you can eschew the standard functions strcpy
and strcat
and assign a string manually:
A[0] = '1';
A[1] = '2';
A[2] = '\0';
If there were characters in the string A
beyond index 2
, they don't matter since string processing functions will stop reading the string once they encounter the null terminator at A[2]
.
Upvotes: 2