Talk:C Programming/Variables
From Wikibooks, the open-content textbooks collection
Contents |
[edit] Semicolon
Think phrase: "semicolon important part of every statement", more appropriate, because every statement has its semicolon, even last.194.85.82.1 00:30, 20 February 2007 (UTC)
[edit] Presentation of Nameing identifiers
Instead of "Naming of Variables" the section should be called "Naming of Identifiers" because the same conventions hold for variables and function names. Kinglag 22:50, 10 March 2006 (UTC)
Forget that 86.129.225.142 18:24, 1 Jul 2005 (UTC)
[edit] C strings
[quote]There is one more kind of literal that needs to be explained in connection with chars: the string literal. A string is a series of characters, usually intended to be output to the string. They are surrounded by double quotes (" ", not ' '). An example of a string literal is the "Hello, world!\n" in the "Hello, World" example.[/quote]
How can one assign string to another string? Will this work and why?
char str[20]; str = "mystring";
[edit] Answer
No this won't work. C is a low level language and you need to copy the data from one string to the next:
char str[20]; strncpy (str, "mystring", 19); str [19] = '\0';
Supprised about the 3rd line? The bitter truth is that none of the predefined string operations in "string.h" could be considerd safe.
- strcpy, strcat
- will copy a larger string into a smaller overwriting memory that follows.
- strncpy
- won't add a '\0' to the end of the string when the source string is longer then the max. lenght specfied.
- strncat
- For once strncat counts the characters read from the source string - which is not as usefull then counting the characters used up in the destination string. And then - just to supprise you and unlike strncpy - will copy n + 1 characters allways adding a '\0'.
- strlen
- will run forever if the '\0' is missing for whatever reason - with strncpy beeing one possible reason.
An realy experienced C programmer - like myself - writes his/her own string operations with propper support for a maximum length on the destination string.
--Krischik T 13:13, 5 October 2005 (UTC)
- However, you can initialize an array of characters with a literal string, like char my_string[20] = "za warudo!";. This won't work with anything except things that are literals after preprocessing, as you all should know, and hardly merits a mention in the module proper. (Perhaps in a section on advanced syntax, or something? If this is actually advanced in any way.) (and please don't advocate reinventing the C library. that's something that students do. experienced programmers roll with whatever is available instead of fighting the tide.) 85.76.93.185 11:59, 22 April 2006 (UTC)