Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typcasting a character array to a const char * [closed]

I have a character arraym char Input[200];

input as of now has the string "abc.txt".

I have a method that strictly needs a const char *, how can I convert my input array into a const char *.

I tried casting it, and passing it, but upon using GDB, I feel like since the remaining 192 slots in input are filled with garbage(or are empty)its not being accepted by the function. When I pass the string literal "a.txt" to the function it works. so at this point I would like to extract the filled up elements from input array and convert it to a const char *.

I am taking input as a filename from a user, so I used a char array to store the input.

   int main()
    {
    char *name;

    char input[1024];
    strcpy(input, argv[1]);

    name = input;

    sys_open(input, "O_RDWR", 00700);


    }
like image 318
user1888502 Avatar asked Feb 09 '13 05:02

user1888502


2 Answers

You should be able to pass it directly. A char[] can be cast to a const char *, but not vice versa.

The reason that you see all of the garbage in gdb is because arrays are not pre-initialized to contain anything, so you're just seeing whatever garbage was in there before. As long as your string is null-terminated, it should be fine.

like image 182
George Madrid Avatar answered Sep 22 '22 11:09

George Madrid


Arrays naturally decays to pointers so that's not a problem.

The problem with the "garbage" is because that's what in the memory where the array is located. The important thing to look after is that the string is terminated by the '\0' character.

So the string "abc.txt" looks like this

'a', 'b', 'c', '.', 't', 'x', 't', '\0'

What comes after this doesn't matter as all string functions stop at the '\0'.

If you are using the array containing the string, it's important to use strlen to get the length, and not sizeof, since the sizeof operator give the length of the whole array and not the contained string.

like image 28
Some programmer dude Avatar answered Sep 19 '22 11:09

Some programmer dude