Interview Question
Country: United States
char *str1 = "I am working in Client Environment";
char *str2 = 0x00;
str2 = (char *)malloc( strlen( str1 ) + 1 ); /* the +1 is for the null terminator */
Remember sizeof returns the size of the data type. A pointer is 4 bytes. strlen gets the length of the string the pointer points to.
Again, you would free() str2 when you're done with it. Also check to see if the pointer you malloc'd or strdup'd is null, which means the allocation failed.
Use strdup.
char *ptr = 0x00;
ptr = strdup( "some string" );
free( ptr );
strdup gets the length of the incoming string (including the null terminator), creates memory for it, and returns a pointer to the memory.
As with any memory allocation, make sure you free() it when you're done with it.
/*C - program to declare int, char and float variables dynamically.*/
- Srinivas September 30, 2016#include<stdio.h>
#include<stdlib.h>
int main(){
//declare pointer variables
int *i;
char *c;
float *f;
//initialize size to pointers
i=(int*) malloc(sizeof(int));
c=(char*) malloc(sizeof(char));
f=(float*)malloc(sizeof(float));
//assign values
*i=100;
*c='N';
*f=123.45f;
//print values
printf("value of i= %d\n",*i);
printf("value of c= %c\n",*c);
printf("value of f= %f\n",*f);
free(i);
free(c);
free(f);
return 0;
}
I could see the above code in that char is defined dynamically but it will hold only one byte since it is declared as c=(char*) malloc(sizeof(char));