Josch Kraus Josch Kraus - 1 year ago 121
C Question

c: typecast pointer to char to const char array

this is the issue:

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

void test_me(const char test_array[]){
printf("%s\n", test_array);


void main(void){
char *string = "Successfull cast!";
const char test_array [100];
* something that fills the const char test_array
* with the contend of *string


The following I have tried yet:

strcpy(test_array, string); /*gcc: "...discards const qualifier..."*/

then this:

test_array[0] = string; /*gcc: "assignment of read-only location.."*/

...and some stuff that is hardly reasonable...

Someone suggests a solution?

EDIT: The point to this is, that the API of another module requests a
const char[]
as a parameter but I have the requested information exclusivly in the form of the pointer. So is there no way I can declare the test_array with the contend of *string? I know const is read-only but at some point a const must be declared ?

Answer Source

The solution is to skip the const keyword on the declaration. If you want to write to it then it clearly is not constant.

    char test_array[100];

Note that you can pass a non-const array to a function that want a const array, but not the other way around.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download