Assign String Value to Pointer

char *tempMonth; char month[4]; month[0]='j'; month[1]='a'; month[2]='n'; month[3]='\0'; 

How to set month tempMonth? thanks

and how to finally print it?

thanks

+6
source share
6 answers

In C, month == &month[0] (in most cases), and they are equal to a char * or character pointer.

So you can do:

 tempMonth=month; 

This will point to the unassigned tempMonth pointer to point to the literal bytes allocated in the other 5 lines of your message.

To make a string literal, it is also easier to do:

 char month[]="jan"; 

Alternatively (although you are not allowed to change characters in this):

 char *month="jan"; 

The compiler will automatically highlight the length of the literal on the right side of month[] using the correct NULL string C and month will point to the literal.

For print:

 printf("That string by golly is: %s\n", tempMonth); 

You might want to look at C strings and C string literals .

+11
source
 tempMonth = month 

When you assign a value to a pointer, it is a pointer, not a string. Assigning, as indicated above, you won’t have wonderfully two copies of the same line, you will have two pointers ( month and tempMonth ) pointing to the same line.

If you need a copy, you need to allocate memory (using malloc ) and then copy the values ​​(using strcpy if it is a zero-terminated string, memcpy or a loop otherwise).

+2
source

If you need a copy of the pointer, you can use:

 tempmonth = month; 

but this means that both point to the same underlying data - change one and this will affect both.

If you need independent strings, you will have a good chance that your system will be strdup , in which case you can use:

 tempmonth = strdup (month); // Check that tempmonth != NULL. 

If your implementation does not 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 } 

To print lines in a formatted format, look at the printf family, although for a simple line such as this will be standard output, puts can be quite good (and probably more efficient).

+2
source
 tempmonth = malloc (strlen (month) + 1); // allocate space strcpy (tempMonth, month); //copy array of chars 

Remember:

 include <string.h> 
+1
source
 #include "string.h" // or #include <cstring> if you're using C++ char *tempMonth; tempMonth = malloc(strlen(month) + 1); strcpy(tempMonth, month); printf("%s", tempMonth); 
+1
source

You can do something like:

 char *months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug","Sep","Oct", "Nov", "Dec"}; 

and access

 printf("%s\n", months[0]); 
0
source

Source: https://habr.com/ru/post/886111/


All Articles