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 c开发者_高级运维ompiler: 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:
*filename = argv[1];
It should be:
filename = argv[1];
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 filename
in the printf()
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.
You're not making filename
point to the same place as argv[1]
. To do that you need
filename = argv[1];
With your version (*filename = argv[1];
) you're trying to make whatever filename points to have the value that is in argv[1]. There's lots of stuff wrong with this: a) filename is not initialized and can point anywhere, even invalid locations; b) argv[1]
is of type char*
and you're trying to put it into a location of type char
!
In the statement *filename = argv[1];
, the expression *filename
attempts to dereference (find the value pointed to) the filename
pointer, which is not yet pointing anywhere meaningful.
Change the assignment to filename = argv[1]
.
You're dereferencing the char* when you try to assign it, so you're trying to stuff a pointer into a char. And since filename is uninitialized, you're trying to hit some random address (or perhaps address 0x00000000. And your print statement, if you got that far, wouldn't work either: you're again dereferencing the char* (to get a char) and then telling printf to interpret that as a pointer to a nul-terminated string.
Try this:
char *filename ;
filename = argv[1] ;
printf( "The filename is: %s" , filename ) ;
精彩评论