The C library function to copy a string is strcpy(), which (I'm guessing) stands for string copy. Here's the format: char * strcpy(char * dst, const char * src);
strcpy in C/C++ strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string. h header file and in C++ it is present in cstring header file.
You could use strdup() to return a copy of a C-string, as in: #include <string. h> const char *stringA = "foo"; char *stringB = NULL; stringB = strdup(stringA); /* ... */ free(stringB);
Below is the basic syntax for declaring a string. char str_name[size]; In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.
This link should satisfy your curiosity.
Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.
But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.
Strings in C are represented as arrays of characters.
char *p = "String";
You are declaring a pointer that points to a string stored some where in your program (modifying this string is undefined behavior) according to the C programming language 2 ed.
char p2[] = "String";
You are declaring an array of char initialized with the string "String" leaving to the compiler the job to count the size of the array.
char p3[5] = "String";
You are declaring an array of size 5 and initializing it with "String". This is an error be cause "String" don't fit in 5 elements.
char p3[7] = "String";
is the correct declaration ('\0' is the terminating character in c strings).
http://c-faq.com/~scs/cclass/notes/sx8.html
You shouldn't use the third one because its wrong. "String" takes 7 bytes, not 5.
The first one is a pointer (can be reassigned to a different address), the other two are declared as arrays, and cannot be reassigned to different memory locations (but their content may change, use const
to avoid that).
char *p = "String"; means pointer to a string type variable.
char p3[5] = "String"
; means you are pre-defining the size of the array to consist of no more than 5 elements. Note that,for strings the null "\0" is also considered as an element.So,this statement would give an error since the number of elements is 7 so it should be:
char p3[7]= "String";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With