views:

33

answers:

4

I have a global variable that is a *char. My main function header reads as int main(int argc, char* argv[argc]){...}. These two lines of code have to remain the way they are. The first argument of my main function is a number of type *char, that I convert to a char using atoi(...);. I am basically changing the ASCII value to its corresponding character. Now I want to store this local variable character I have into the global variable that is a char pointer. I know the problem is related to allocation of memory, but I am not sure how to go about this.

My code:

char* delim;
int main(int argc, char* argv[argc])
{
  char delimCharacter;
  if (isdigit(*(argv[3])) == 0) delim = argv[3]; //you can pass in a character or its ascii value
  else {   //if the argument is a number, then the ascii value is taken
    delimCharacter = atoi((argv[3]));
    printf("%s\t,%c,\n", argv[3], delimCharacter);
    //sprintf( delim, "%c", delimCharacter );  // a failed attempt to do this
    *delim = delimCharacter;
    //strncpy(delim, delimCharacter, 1);                // another failed attempt to do this
  }
  //printf("%s\n",delim);

This yields a seg fault.

+1  A: 

You need to verify you have got (at least) 3 arguments before you start using them.

if (argc < 4)
{
    printf("Need 3 args");
    exit(1);
}

Then you need to allocate some memory to put the character in.

delim = malloc(2);
// TODO: Should check the result of malloc before using it.
*delim = delimCharacter;
delim[1] = 0; // Need to NULL terminate char*
Douglas Leeder
A: 

You're dereferencing an uninitialized pointer. delim never gets initialized when it goes into the else block.

bshields
A: 
char delim[] = ","; // anything really, as long as as it's one character string

...


delim[0] = delimCharacter;
Arkadiy
A: 

In addition to your memory issue, I think you are confused about what atoi does. It parses a string representation of a number and returns the equivalent int value, e.g. "10000" => 10,000. I think that you think it will give you the ASCII value of a character, e.g. "A" =>65.

Since you have a char *, and you are (I think) assuming that it contains a single character, you could simply do this:

delimCharacter = *(argv[3]);

However, there really seems to be no need to use the intermediate step of assigning this value to a char variable at all. If the end goal is to have delim point to the char that is the delimiter, then it seems this is all you need to do:

delim = argv[3];

Not only does this remove unnecessary code, but it means you would no longer need to allocate additional memory for delim to point to.

I would also declare delim as a const char * since I assume there is no reason to change it.

Dave Costa