So I\'m trying to figure this out with a simple program:
#include
#include
#include
int main()
{
char a[]=
Try using strcpy instead of assigning them by dereferencing.
The declaration char a[] = "lalala";
creates an array of characters, where the name a
is an alias for the memory address where the first character is stored.
To create an array of strings, you can make an array of character pointers, each of which holds the memory address of the starting position of a single character array.
#include <stdio.h>
int main(void)
{
/* Store the starting address of each character array in an array of
* character pointers */
char alpha[] = "Alpha"; /* Array of characters */
char beta[] = "Beta";
char gamma[] = "Gamma";
char *char_ptr_array[3]; /* Array of pointers to characters */
char_ptr_array[0] = &alpha[0];
char_ptr_array[1] = beta;
/* This does the same thing since the array's name is an alias
* for the address of the first element */
char_ptr_array[2] = gamma;
printf("%s, %s, %s\n", char_ptr_array[0], char_ptr_array[1], char_ptr_array[2]);
return(0);
}
You can also make the assignment like this, which is a shorthand for doing the same thing:
#include <stdio.h>
int main (void)
{
char *alphabet[3] = { "Alpha", "Beta", "Gamma" };
printf("%s, %s, %s\n", alphabet[0], alphabet[1], alphabet[2]);
return(0);
}
You could use an array of strings:
std::string test[20];
And avoid using #include <string.h>
; use just #include <string>
.
To store entire string use string copy.
char a[]="lalala";
char c[]="nanana";
char d[3][10];
strcpy(d[0],a);
strcpy(d[1],b);
strcpy(d[2],c);
printf("%s -- %s -- %s", d[0], d[1], d[2]);