char *tempMonth;
char month[4];
month[0]='j';
month[1]='a';
month[2]='n';
month[3]='\0';
how to assign month to tempMonth? thanks
and how to print it out finally?
thanks
In C, month == &month[0]
(in most cases) and these equals a char *
or character pointer.
So you can do:
tempMonth=month;
This will point the unassigned pointer tempMonth
to point to the literal bytes allocated in the other 5 lines of your post.
To make a string literal, it is also simpler to do this:
char month[]="jan";
Alternatively (though you're not allowed to modify the characters in this one):
char *month="jan";
The compiler will automatically allocate the length of the literal on the right side of the month[]
with a proper NULL terminated C string and month
will point to the literal.
To print it:
printf("That string by golly is: %s\n", tempMonth);
You may wish to review C strings and C string literals.
If you just want a copy of the pointer, you can use:
tempmonth = month;
but that means both point to the same underlying data - change one and it affects both.
If you want independent strings, there's a good chance your system will have strdup
, in which case you can use:
tempmonth = strdup (month);
// Check that tempmonth != NULL.
If your implementation doesn't have strdup
, get one:
char *strdup (const char *s) {
char *d = malloc (strlen (s) + 1); // Allocate memory
if (d != NULL) strcpy (d,s); // Copy string if okay
return d; // Return new memory
}
For printing out strings in a formatted fashion, look at the printf
family although, for a simple string like this going to standard output, puts
may be good enough (and likely more efficient).
tempMonth = month
When you assign a value to a pointer - it's a pointer, not a string. By assigning as above, you won't miraculously have two copies of the same string, you'll have two pointers (month
and tempMonth
) pointing to the same string.
If what you want is a copy - you need to allocate memory (using malloc
) and then actually copy the values (using strcpy
if it's a null-terminated string, memcpy
or a loop otherwise).
tempmonth = malloc (strlen (month) + 1); // allocate space
strcpy (tempMonth, month); //copy array of chars
Remember to:
include <string.h>
#include "string.h" // or #include <cstring> if you're using C++
char *tempMonth;
tempMonth = malloc(strlen(month) + 1);
strcpy(tempMonth, month);
printf("%s", tempMonth);
You could do something like:
char *months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug","Sep","Oct", "Nov", "Dec"};
and get access
printf("%s\n", months[0]);