I am trying to create a pointer to one of the main() arguments in my program.
I set up the initial pointer, then I set it equal to the 2nd element in the array, but I get an error when I try to compile, segmentation fault. Does this occur because a pointer is pointing to a bad address?
Here is the code:
char *filename;
*filename = argv[1];
printf("The filename is: %s", *filename);
I get errors about the pointer trying to cast the argument as an int. Is this because the pointer is actually an integer address value and I am trying to set it equal to a string?
Edit: When I change to “filename = argv[1]”, then I get the following error from my compiler: assignment discards qualifiers from pointer target type.
A segmentation fault couldn’t possibly occur when you compile. Unless, well, the compiler violates memory safety, which is unlikely. I’ll take it that it happens when you run the program :D.
The problem is here:
It should be:
Why? You declared a pointer to
char, unitialized, poiting nowhere in particular. Then, you dereferenced that pointer and assigned data to that memory position. Which is, well, who knows where!Edit: you also dereference
filenamein theprintf()call. Remove that*:).Also, didnt’ the compiler shoot a warning when you assigned *filename? Making integer from pointer without a cast, would be my guess? Pay attention to the warnings, they provide useful information!
Cheers.