Srinivas
BAN USER
- 0of 0 votes
AnswersCan any one tell me how to initialize a char variable dynamically to hold any stringlength of unknown value.
- Srinivas in United States| Report Duplicate | Flag | PURGE
- 0of 0 votes
AnswersHow to print from 3rd column to till last columns using awk command in unix, if there are 'n' columns in a file.
- Srinivas in United States| Report Duplicate | Flag | PURGE
unknown xyz - 0of 2 votes
AnswersFind the highest time difference in the below log file Using single Unix command
- Srinivas in United States
STARTTIME:2015-12-01 04:13:15
ENDTIME :2015-12-01 04:14:16
----------------------------------------------
----------------------------------------------
STARTTIME:2015-12-01 04:11:15
ENDTIME :2015-12-01 04:11:17
----------------------------------------------
----------------------------------------------
STARTTIME:2015-12-01 04:12:15
ENDTIME :2015-12-01 04:15:15
----------------------------------------------
----------------------------------------------
STARTTIME:2015-12-01 04:10:10
ENDTIME :2015-12-01 04:10:11
----------------------------------------------
----------------------------------------------| Report Duplicate | Flag | PURGE
Amazon Development Support Engineer Unix
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.
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.
/*C - program to declare int, char and float variables dynamically.*/
#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));
uppose I just need to read a string from the user and need to store it for the above case.If your user's input is going into a 'char *ptr', then you would use
- Srinivas October 03, 2016char *newPtr = strdup( ptr );You can use gets( ), scanf( ), etc. for reading input from the console.