Skip to content

Commit f2de244

Browse files
committed
feat: update code for strings
1 parent 2673ba6 commit f2de244

4 files changed

Lines changed: 41 additions & 0 deletions

File tree

07-Strings-2/modify_str.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#include <stdio.h>
2+
int main(void){
3+
char a_string[] = "Sweet home";
4+
char *ptr1 = a_string;
5+
char *ptr2 = "Sweet home";
6+
*(ptr1+6) = 'd';
7+
*(ptr2+6) = 'd'; // This line causes an error!
8+
for (int i = 0; i < 10; i++){
9+
printf("%c", ptr1[i]);
10+
}
11+
}

07-Strings-2/print_str_via_ptr.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#include <stdio.h>
2+
int main(void){
3+
char a_string[] = "Sweet home";
4+
char *ptr = a_string;
5+
for (int i = 0; i < sizeof(a_string); i++){
6+
printf("%c", *(ptr + i));
7+
}
8+
}
9+
10+
// while(*ptr != '\0'){
11+
// printf("%c", *ptr);
12+
// ptr++;
13+
// }
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#include <stdio.h>
2+
int main(void){
3+
char a_string[10] = "Sweet home";
4+
char *ptr = a_string;
5+
for (int i = 0; i < sizeof(a_string); i++){
6+
printf("%c", ptr[i]);
7+
}
8+
}

07-Strings-2/subscripting.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#include <stdio.h>
2+
int main(void){
3+
int arr[5] = {1, 2, 3, 4, 5};
4+
int *p = &arr[0];
5+
printf("arr[0] = %d\n", arr[0]);
6+
printf("p[0] = %d\n", p[0]); // *(p + 0)
7+
printf("arr[1] = %d\n", arr[1]);
8+
printf("p[1] = %d\n", p[1]); // *(p + 1)
9+
}

0 commit comments

Comments
 (0)