In: Computer Science
Question 3: C-Strings and pointers (10 pts)
Note: For both part a) and part b) you may not use any library function calls (e.g. you cannot use strlen, strcat, etc.)
// Append strt2 to str1
void my_strcat(char str1[], char str2[])
{
//YOUR CODE HERE
}
// example of using my_strcat()
#include <stdio.h>
int main(void)
{
char my_str1[50] = “hello ”;
char my_str2[] = “world”;
my_strcat(my_str1, my_str2);
// Printf should print: hello world.
printf(“%s \n”, my_str1);
}
Note: In general, a function’s parameter declarations “char str[]” and “char *str” are equivalent (i.e. they are interchangeable)
// Append strt2 to str1
void my_strcat(char* str1, char* str2)
{
// YOUR CODE HERE
}
// example of using my_strcat()
#include <stdio.h>
int main(void)
{
char my_str1[50] = “hello ”;
char my_str2[] = “world”;
my_strcat(my_str1, my_str2);
// Printf should print: hello world.
printf(“%s \n”, my_str1);
}
a) [5] The following function appends C-string str2, to C-string str1. Complete the function using array access, i.e. str1[i], but no pointer access.
Ans.
#include <stdio.h>
void my_strcat(char str1[], char str2[])
{
int c, d;
c = 0;
while (str1[c] != '\0') {// Run till str1 is
complete
c++;
}
d = 0;
while (str2[d] != '\0') { // concate to
str1
str1[c] = str2[d];
d++;
c++;
}
str1[c] = '\0'; // add null to concate
str1
}
int main(void)
{
char my_str1[50] = "hello " ;
char my_str2[] = "world";
my_strcat(my_str1, my_str2);
// Printf should print: hello world.
printf("%s \n", my_str1);
}
/* OUTPUT */
b) [5] Rewrite the above function, this time using pointer access, i.e. *str, but no array access.
ans.
#include <stdio.h>
void my_strcat(char* str1, char* str2)
{
while(*str1)
str1++;
while(*str2)
{
*str1 = *str2;
str2++;
str1++;
}
*str1 = '\0';
}
int main(void)
{
char my_str1[50] = "hello " ;
char my_str2[] = "world";
my_strcat(my_str1, my_str2);
// Printf should print: hello world.
printf("%s \n", my_str1);
}
/* PLEASE UPVOTE */