Stephane B. Stephane B. - 1 year ago 117
C Question

C - Convert int to char

I am looking for a solution for my problem (newbie here).

I have an array of strings (

char** arrayNum
) and I would like to store the number of elements of that array at the first index.

But I can't find the right way to do convert the number of elements as a string (or character).

I have tried
, casting (
... nothing works.

As every time I ask a question on Stack Overflow, I am sure the solution will be obvious. Thanks in advance for your help.

So I have an array of strings
char** arrayNum
which I populate, leaving the index

When I try to assign a string to

  • This works:
    arrayNum[0] = "blabla";

  • This does not work:
    arrayNum[0] = (char) ((arraySize - 1)+'0');

I have tried countless others combinations, I don't even remember...

Answer Source

arrayNum can be thought of as an array of strings (char *). So you will naturally have trouble trying to assign a char (or indeed any type other than char *) to an element of this array.

I think it would preferable to store the length of the array separately to the array. For example, using a struct. To do otherwise invites confusion.

If you really, really want to store the length in the first element, then you could do something like:

arrayNum[0]    = malloc(sizeof(char));
arrayNum[0][0] = (char) ((arraySize - 1)+'0');

This takes advantage of the fact that arrayNum is strictly an array of pointers and each of those pointers is a pointer to a char. So it can point to a single character or an array of characters (a "string").

Compare this for clarity with (say):

struct elements {
    int length;
    char **data;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download