Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign a string value to pointer

Tags:

c

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

like image 946
hkvega Avatar asked Apr 18 '11 03:04

hkvega


2 Answers

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.

like image 53
the wolf Avatar answered Sep 29 '22 18:09

the wolf


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).

like image 34
paxdiablo Avatar answered Sep 29 '22 18:09

paxdiablo