C String Assignment: Quick Guide

In the C programming language, there are several ways to assign values to strings.

  1. You can initialize a string variable by directly assigning values to a character array, for example:
char str[] = "Hello, World!";
  1. Pointer usage: You can also use pointer variables to point to a string constant, for example:
char *str = "Hello, World!";

It is important to note that for string constants pointed to by a pointer, they cannot be modified because string constants are stored in read-only memory regions, attempting to modify them will cause the program to crash.

  1. By using the strcpy function, you can copy one string to another string variable, for example:
char str1[20];
char str2[20] = "Hello, World!";
strcpy(str1, str2);

Here are several common ways to assign strings, choose the appropriate method based on the situation when assigning string variables.

bannerAds