Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

COMPUTER SCIENCE C CODE FUNCTION Hello, i need help with this function. Written

ID: 3666712 • Letter: C

Question

COMPUTER SCIENCE C CODE FUNCTION

Hello, i need help with this function. Written in C

kstring kstrfrom(const char *cstr)

Creates and returns a new kstring object that contains a copy of the contents of a null-terminated C string, including the null terminator.

The .length member of the returned kstring should be the length of cstr, plus one for the null terminator. The .data member should be a pointer to newly-allocated memory, into which you have copied the contents of cstr, including the null byte at the end.

If there is an error allocating memory, this function should call abort() or throw an uncaught exception.

Explanation / Answer

kstring kstrfrom(const char *cstr) {
   int length = strlen(cstr);
  
   kstring cdest = (char*)malloc((length+1)*sizeof(char));
   if(cdest == NULL){
       abort();
   }
   int i = 0;
   while(cstr[i] != ''){
       cdest[i] = cstr[i];
       i++;
   }
   cdest[i] = ''; // this is null from source string
   cdest[++i] = ''; // this is terminator for cdest
  
   return cdest;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote