Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dynamic array

Status
Not open for further replies.

slok

Programmer
Jul 2, 1999
108
SG
I have a program which takes in arguments.
The first argument is a string of legal characters
eg. myprog abcdef ..."a", "b", "c", "d" etc..
are all legal characters in this case.

how can I assign this string to a variable?

my main function is as follows:

int main(int argc, char *argv[]){

}
 
also, how can I extract the first character from the
1st argument?

will need to use the 1st character as a default entry
if user don't key in anything within a timeframe.
 
Hey, try to be a bit more explanatory...however I couldn't get what you wish to do, I will answer two of ur question the way I have interpreted them.

to assign the argument accepted from user to string, say
#include <stdio.h>
#include <string.h>
int main(int argc, char argv[])
{
char *str;
char ch;
strcpy(str,argv[1]);
// to get the first character use
ch = argv[1][0];
printf(&quot;The string is : %s and character is %c&quot;,str,ch);
}

Hope that helps,
If u need something else try to give a sample code and better prob. def.
Regards,
SwapSawe.
 
Swap, in this line you're copying into an uninitialized pointer:

char *str;

/* ... */

strcpy(str,argv[1]);

You have to allocate memory for str first:

#include <stdlib.h>
#include <string.h>

/* ... */

str=malloc(strlen(argv[1])+1);

if (str!=NULL) {
strcpy(str,argv[1]);
/* ... */

Or just set str to point to it:

str=argv[1];

Or you could just get this stuff without using separate variables:

printf(&quot;The string is : %s and character is %c&quot;,argv[1],argv[1][0]);

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top