Help with pointers and dynamic arrays: Assume that char*s1, *s2; are given dynam
ID: 3559426 • Letter: H
Question
Help with pointers and dynamic arrays:
Assume that char*s1, *s2; are given dynamically allocated size 50 arrays and populated with some random chars.
1)Write code that copies the string stored in character array s1 into character array s2
(erases olds2)
.
2)Compare the string stored in character array s1 with the string in character array s2, and print
the result to the display (e.g. they are same or not).
3) Create a newly created dynamic char array s3 that will append the string in character array s2 to the string in character array s1
Explanation / Answer
Assume that char*s1, *s2; are given dynamically allocated size 50 arrays and populated with some random chars.
1)Write code that copies the string stored in character array s1 into character array s2
(erases olds2)
int i;
free(s2);
s2 = malloc(sizeof(char)*50);
for(i=0; s1[i]!=''; i++)
s2[i] = s1[i];
s2[i] = '';
2)Compare the string stored in character array s1 with the string in character array s2, and print
the result to the display (e.g. they are same or not).
if(strcmp(s1,s2)==0)
printf("%s and %s are same",s1,s2);
else
printf("%s and %s are not same",s1,s2);
3) Create a newly created dynamic char array s3 that will append the string in character array s2 to the string in character array s1
s3 = malloc(sizeof(char)*100);
strcpy(s3,s1);
strcat(s3,s2);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.