Whether to use a character array or a string constant

Source: Internet
Author: User

There are two methods in C that represent strings, one is a character array, and the other is a string constant

The character array and string constants are sufficient to meet the requirements in the programming process if only the strings are read, and if there is a write (modify) operation, only character arrays are used, and string constants cannot be used.

The difference between a string array and a string constant:

The fundamental difference is that in memory the storage area is different, the character array is stored in the global data area or the stack area, and the second form of the string is stored in the constant area. The string (and other data) of the global data area and the stack area has read and write permissions, while the constant-area string (which also includes other data) has only read permission and no write permission.
The following example shows how to output such a string:

  1. #include<stdio.h>
  2. intmain() {
  3. Char*str ="Http://c.biancheng.net";
  4. int len =strlen(str), i;
  5. ?
  6. Direct output string
  7. printf("%s\n", str);
  8. Using * (Str+i) is a string array
  9. for (i= 0; I< len; I ++) { /span>
  10. printf("%c",* (str+i));
  11. }
  12. printf("\ n") ;
  13. Use Str[i] is a string constant
  14. for (i=0; i<len; i+ +) {
  15. printf("%c", str[i]);
  16. }
  17. printf("\ n") ;
  18. ?
  19. return 0;
  20. }

    Operation Result:
    Http://c.biancheng.net
    Http://c.biancheng.net
    Http://c.biancheng.net
    The string that gets the user input is a typical write operation that uses only character arrays and cannot use string constants, see the following code:

  21. #include<stdio.h>
  22. intmain() {
  23. Char str[n];
  24. Gets(str);
  25. printf("%s\n", str);
  26. ?
  27. return 0;
  28. }

    Operation Result:
    C C + + Java Python JavaScript
    C C + + Java Python JavaScript

Whether to use a character array or a string constant

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.