Podcast
Questions and Answers
Given the declaration char str[10];
, and the subsequent assignments str[0] = 'H'; str[1] = 'e'; str[2] = 'l'; str[3] = 'l'; str[4] = 'o'; str[5] = '\0';
, what is the critical distinction between the length and the size of the string str
?
Given the declaration char str[10];
, and the subsequent assignments str[0] = 'H'; str[1] = 'e'; str[2] = 'l'; str[3] = 'l'; str[4] = 'o'; str[5] = '\0';
, what is the critical distinction between the length and the size of the string str
?
- The length is 5, representing characters before '\0', and the size is 6, counting the '\0'.
- The length is 10, representing allocated memory, and the size is 5, representing characters before '\0'.
- The length is 6, counting the '\0', and the size is 10, representing total allocated memory.
- The length is 5, representing characters before '\0', and the size is 10, representing total allocated memory. (correct)
If char name[] = "cp264";
, how does the compiler handle memory allocation, and what are the implications for modifying this string?
If char name[] = "cp264";
, how does the compiler handle memory allocation, and what are the implications for modifying this string?
- The compiler allocates a read-only memory block of 5 bytes to store the string, modifications are permitted.
- The compiler allocates a memory block of 5 bytes, equivalent to the string length, and modifications are not supported.
- The compiler allocates a mutable memory block of 6 bytes with an additional null terminator, modifications are permitted. (correct)
- The compiler allocates a mutable memory on the stack comprising 7 bytes with an additional null terminator, and modifications are not allowed.
Given char *p = "cp264";
, what is the critical difference in memory allocation and modifiability compared to char name[] = "cp264";
?
Given char *p = "cp264";
, what is the critical difference in memory allocation and modifiability compared to char name[] = "cp264";
?
- Both `p` and `name` point to read-only memory locations, preventing modifications to the string.
- Both `p` and `name` point to mutable memory locations, allowing modifications to the string.
- `p` points to a mutable memory location where the string is stored, while `name` is allocated on the stack and cannot be modified.
- `p` points to a read-only memory location, preventing modifications, while `name` allocates modifiable memory on the stack. (correct)
Consider char *s = "example";
. What is the potential consequence of attempting to modify the string using s[0] = 'X';
?
Consider char *s = "example";
. What is the potential consequence of attempting to modify the string using s[0] = 'X';
?
If char str[] = "hello"; char *ptr = str;
, what is the key distinction in how str
and ptr
can be used and modified?
If char str[] = "hello"; char *ptr = str;
, what is the key distinction in how str
and ptr
can be used and modified?
Suppose you have char str[] = "testing";
and char *ptr = "testing";
. Which operation is valid, and what does it achieve?
Suppose you have char str[] = "testing";
and char *ptr = "testing";
. Which operation is valid, and what does it achieve?
If given the code char *message = "Hello";
and then message[0] = 'J';
, what is the most likely outcome and why?
If given the code char *message = "Hello";
and then message[0] = 'J';
, what is the most likely outcome and why?
Consider the following code snippet:
char string1[] = "example";
char *string2 = "example";
What is the most significant difference between string1
and string2
regarding their usage and modifiability?
Consider the following code snippet:
char string1[] = "example";
char *string2 = "example";
What is the most significant difference between string1
and string2
regarding their usage and modifiability?
Given two declarations: char immutable[] = "constant";
and char *mutable_ptr;
, how can mutable_ptr
be correctly initialized to safely modify the string, and what precautions should be taken?
Given two declarations: char immutable[] = "constant";
and char *mutable_ptr;
, how can mutable_ptr
be correctly initialized to safely modify the string, and what precautions should be taken?
If char *str = "123";
, what does str + 1
represent, and how does dereferencing it with *(str + 1)
affect the value?
If char *str = "123";
, what does str + 1
represent, and how does dereferencing it with *(str + 1)
affect the value?
Flashcards
What is a C string?
What is a C string?
A sequence of characters ending with a null character ('\0').
How are strings stored?
How are strings stored?
A character array is used to store a string, with each character in a consecutive position. The end is marked by '\0'.
String Length
String Length
The number of characters before the null terminator ('\0').
String Representation
String Representation
Signup and view all the flashcards
char name[] = "cp264";
char name[] = "cp264";
Signup and view all the flashcards
Array Size vs String Length
Array Size vs String Length
Signup and view all the flashcards
char pointer and string
char pointer and string
Signup and view all the flashcards
*p in string context
*p in string context
Signup and view all the flashcards
*(p+3) in string context
*(p+3) in string context
Signup and view all the flashcards
char *p = "cp264";
char *p = "cp264";
Signup and view all the flashcards
Study Notes
Concepts of Strings
- A string in C is a sequence of characters that ends with a null character and stored in a char array.
- A char array is used to hold the string with the character stored in an array.
- The null character
\0
indicates the end of a string. - The ASCII value of
\0
is 0, which is also the value of NULL as a pointer. - The length of a string is the number of characters before the null character.
- A char pointer is used to represent and access a string by pointing to the memory location of the first character.
- Given the example
char str[10];
, a char array of 10 bytes is declared str[5] = '\0';
serves as the terminator- In the example, printing
str
outputs "Hello" and the array namestr
is a char pointer to the first character. - The first five elements of array
str
would hold 'H', 'e', 'l', 'l', 'o' - The sixth element is the string terminator
\0
. - The length of the string
str
is 5, while the size of the arraystr
is 10. - When initializing a char array by string like
char name[] = "cp264";
orchar name[6] = {'c', 'p', '2', '6', '4', '\0'};
- The compiler allocates 6 elements for the char array name.
- The characters 'c', 'p', '2', '6', '4', and
\0
are assigned to the elements. - The string that
name
holds is 5 and the arrayname
is 6.
String Pointers
- Since a string utilizes a char array, char pointers and associated operations are able to be applied.
- In the example,
char name[20] = "cp264"; char *p = &name[0];
,p
is equalsname
- The output for
printf("%s\n", p);
is:cp264
- The output for
printf("%c\n", *p);
is:c
- The output for
printf("%c\n", *(p+3));
is:6
- The output for
printf("%s\n", p+2);
is:264
- After setting
*p = 'C'; *(p+1) = 'P';
,printf("%s\n", p);
will outputCP264
- The char type pointer has a size of 1 byte, so
p+1
increments the value ofp
by 1. - When a string declared with
char *p = "cp264";
the compiler allocates read-only memory. - It will hold the string "cp264", and the char pointer
p
points to this array, meaning operations like*(p+1) = 'P';
are not allowed.
String Traversal
- Given this script:
void display_string(char s[]) {
char *p = s;
while( *p != '\0') { printf("%c", *p); p++; }
}
char str[] = "cp264";
display_string(str);
- The output will be
cp264
- Since strings have terminators, the length does not need to be explicitly passed to the function.
- Other function implementations include:
void display_string(char *s) {
char *p = s;
while( *p != '\0') { printf("%c", *p); p++; }
}
void display_string(char *s) {
while( *s != '\0') { printf("%c", *s); s++; }
}
void display_string(char *s) {
while(*s) { printf("%c", *s++); }
}
Array of Strings
- An array of strings consists of strings stored in a 2D char array, with each row holding one string.
- For exmaple:
char names[20][40] = {
"cp264",
"data structures II",
"C programming language"
};
- This declares a 2D char array that can hold up to 20 strings, each with a maximum length of 39 and initializes the first three rows.
names[i]
is a pointer that points to rowi
.
Array of Char Pointers
- An array of char pointers is used to represent lists of strings.
- Given:
char *sp[2];
char *s0 = "cp264";
char *s1 = "data structures II";
sp[0] = s0;
sp[1] = s1;
for (int i =0; i<2;i++) printf("%s “, sp[i]);
- The output would be:
cp264 data structures II
Command Line Arguments
- Command line arguments are an application of a char pointer array.
main(int argc, char *argv[])
argc
represents the number of command line arguments, counting each item separated by a space.argv
represents an array of char pointers, whereargv[i]
points to thei
th argument string.- In the command
a.out argument1 argument2
,argc
has a value of 3. - Also
argv[0]
points to the string "a.out",argv[1]
points to "argument1" andargv[2]
points to "argument2".
String Operations
- String operations include:
- Read string from stdin
- Write string to stdout
- Length of a string
- Change case
- Copy string
- Concatenate string
- Compare string
- Reverse string
General Algorithm for String Processing
- Given input
string str[]
orchar *str
:
- Set a char pointer
*ptr = str
. - Enter a
while
loopwhile (*ptr)
to traverse or scan the string.
- If a pattern is matched, take action; and then increment the pointer:
ptr++;
.
- Stop the Loop
Reading Strings from Stdio (Keyboard)
- Three functions are available in stdio to read strings from stdin keyboard:
getchar()
: Retrieves and returns one character.gets(char *p)
: Retrieves a string.scanf("%s", char *p)
: Retrieves a string.- Only
getchar()
reads one character from the buffer at a time and requires iterative calls until a stop character\n
is encountered. - Both
gets()
andscanf()
insert typed characters into the array str from str[0] and insert '\0' at the end.
Output String to Stdout (Screen)
- Three functions for stdout screen output are provided:
putchar()
: Prints a character.puts(str)
: Prints a string.printf("%s", str)
: Formatted printing is used.
Compute the Length of a String
- The length is the number of non-null characters.
String Copy
- Code sample showing how to copy a string.
char a[] = "C programming language";
char c[30];
int i;
for (i = 0; *(a+i) !='\0'; i++) {
- (c+i) = *(a+i);
}
- (c+i) = '\0'; // add null to the end
- Code sample using pointers.
char *p1, *p2;
p1 = a;
p2 = c;
for (; *p1!='\0'; p1++,p2++) {
- p2 = *p1;
}
- p2 = '\0'; // add null to the end
- There are multiple versions of copy_string function:
void copy_string(char *from, char *to){
for (; *from!='\0'; from++, to++) {
- to = *from;
}
- to = '\0';
}
void copy_string(char *from, char *to){
while ((*to = * from) != '\0') { to++; from++; }
}
void copy_string(char *from, char *to){
while ((*to++ = *from++) != '\0') ;
}
Converting Little Case to Upper Case
- Code to show how to convert upper case letters:
void upper_case(char *s) {
if (s == NULL) return;
while (*s) {
if (*s >= 'a' && *s <= 'z' )
- s -= 32;
s++;
}
}
Concatenate String
- Concatenating a source string to destination involves traversing to the end of the destination string and then copying the source string.
void append_string(char *from, char *to) {
if (from == NULL || to == NULL) return;
while (*to) to++; // traverse to the null position of to string
while ((*to++ = *from++) != '\0'); // copy string
}
Comparing Two Strings
- Compares strings based on dictionary/lexical order.
int compare_string(char *s1, char *s2) {
while (*s1 || *s2) {
if (*s1 > *s2)
return 1;
if (*s1 < *s2)
return -1;
s1++;
s2++;
}
return 0;
}
- The output is 0 if the first string and second string are the same, 1 if first string is greater than second string and -1 if the first string is less than the second string.
Reversing a String
- To reverse a string in place, swap the first and last characters by moving towards the middle.
void reverse_string(char *s) {
if (s == NULL) return;
char *p = s, temp;
while (*p++);
p--;
while (s < p) {
temp = *s;
- s = *p;
- p = temp;
s++;
p--;
}
}
String Library Fucntions
- Required Header: `#include <string.h>
- String copy function:
char *strcpy( char *destination, char *source );
- Used to copy the source string to the destination location.
- Memory copy function:
void *memcpy(void *destination, const void *source, size_t n);
- Copies
n
characters from source location to destination. - String Length function:
int strlen( const char *str);
- Returns string length.
- Concatenate two strings
char *strcat( char *destination, char *source );
- Source is used and appended to the destination.
- Compare two strings
int strcmp(const char *first, const char *second );
- Returns -1 if first < second
- Returns 0 if first = second
- Returns 1 if first > second
- Finds the first occurrence of a substring
char *strstr(const char *s1, const char *s2)
- Returns
NULL
pointer ifs1
does not contains2
. - Else, returns a pointer that matches that substring
- Returns
s1
ifs2
isNULL
. - String token function:
char *strtok(char *str, const char *delim)
- Returns a pounter that corresponds to the first word that has been seperated by the delimiters in delim
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.
Related Documents
Description
Understand the nuances of C strings, focusing on the difference between size and length, how strings are stored in memory using character arrays and pointers, and the implications for string modification. Learn to avoid common errors related to string manipulation in C. Explore the behavior of string literals and dynamic memory allocation in regards to string.