C Programming Program: malloc, free, pointer in C char *str= “this is a test onl
ID: 3794650 • Letter: C
Question
C Programming
Program: malloc, free, pointer in C
char *str= “this is a test only –just a test”; /* or other string */
char *ptr1[100];
char *ptr2[100];
– Parse strwith a pointer, and set ptr1 to each word (NULL terminated) within the str(i.e., skip white spaces)
• ptr[0] points to “this”, ptr[1] points to “is”, ptr[2] points to “a”, etc
– Loop: print ptr1[i] that points to valid word
– Loop: for each ptr2[i], mallocand copy the string from ptr1[i], print ptr2[i]
– loop: free each of ptr2[i]
Explanation / Answer
Functions used in the program:
strtok(str , delimiter): To parse the string str separated by a delimiter.
strncpy(str1 , str2 , len2): Copy to the destination string (str1) the values of source string (str2) upto first len2 elements.
malloc(): Allocate the memory to the pointer.
free(): Free the memory allocated using malloc().
Follwing code is explained with the comments inside the code.
----------------------------------------------------------------------
C Code:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main(){
// Test string
char *str="this is a test only –just a test";
char buffer[256]; // some buffer
char *ptr1[100];
char *ptr2[100];
int i=0,j=0;
char *temp;
strcpy(buffer,str); // copy the str contents to the buffer
temp=strtok(buffer," "); // get the first token
while(temp!=NULL){ // while we have a valid token
ptr1[i]=temp; // ptr1[i] points to the token
i++;
temp=strtok(NULL," "); // get next token
}
j=i;
i=0;
// print the values pointed by ptr1[i]
while(i<j){
printf("ptr1[%d] = %s ",i,ptr1[i]);
i++;
}
printf("------------ ");
i=0;
// allocate the memory to ptr2[i] and copy the contents of value pointed by ptr1[i]
while(i<j){
ptr2[i]=(char *)malloc((strlen(ptr1[i])+1)*sizeof(char));
strncpy(ptr2[i],ptr1[i],strlen(ptr1[i]));
i++;
}
ptr2[i]=NULL;
i=0;
// print the contents of ptr2[i]
while(ptr2[i]!=NULL){
printf("ptr2[%d] = %s ",i,ptr2[i]);
i++;
}
// deallocate the memory
for(j=0;j<i;j++){
free(ptr2[j]);
}
return 0;
}
----------------------------------------------------------------------
OUTPUT:
ptr1[0] = this
ptr1[1] = is
ptr1[2] = a
ptr1[3] = test
ptr1[4] = only
ptr1[5] = –just
ptr1[6] = a
ptr1[7] = test
------------
ptr2[0] = this
ptr2[1] = is
ptr2[2] = a
ptr2[3] = test
ptr2[4] = only
ptr2[5] = –just
ptr2[6] = a
ptr2[7] = test
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.