How to create an array of strings"

Hi guys,
Can you please help me with this piece of code.

1
2
3
4
5
6
7
8
9
10
11
    char **row_name;
    char trans[10];
 
    row_name = malloc((100) * sizeof(char *));  
    for (i = 0; i < 100; i++) 
        row_name[i] = malloc(10 * sizeof(char));  
    for (i=0; i<100; i++) {
        sprintf(trans,"constr%d",i);
        strcpy(row_name[i], "trans");
        printf("%s\n", row_name[i]);
      }


What I want ot do is to get a list of names {constr1, constr2,..., constr100}.
row_name must be declared as a pointer. "trans" is an array that I want to use just to pass the string I get with sprintf to strcpy.
I am working under Visual studio 2008.

When I compile, I get the following error messages:
1
2
3
4
5
c
 1>.\Read_Copy.cpp(126) : error C2440: '=' : cannot convert from 'void *' to 'char **'
> Conversion from 'void*' to pointer to non-'void' requires an explicit cast
2>.\Read_Copy.cpp(128) : error C2440: '=' : cannot convert from 'void *' to 'char *'
> Conversion from 'void*' to pointer to non-'void' requires an explicit cast
c

Error message 1 points to line 4
Error message 2 points to line 6
Any help to find the problem will be highly appreciated.

Andre
Last edited on
the malloc function returns a void*.
In C/C++, the compiler will not implicitly assing a void* to a pointer_to_some_other_type.
So for example line 4 means something like this:

char** = void*; //not legal.

You will need to cast - and as you seem to be making a C program rather than a C++ one:

row_name = (char**) malloc((100) * sizeof(char *));

and:
row_name[i] = (char*) malloc(10 * sizeof(char));


SOMETHING ELSE:
This:
1
2
3
       
 sprintf(trans,"constr%d",i);
strcpy(row_name[i], "trans");


does not need two lines of code.
This will do:
1
2
        
sprintf(row_name[i],"constr%d",i);


So all in all:
1
2
3
4
5
6
7
8
9
10
11
    char **row_name;
    int i =0;
 
    row_name = (char**) malloc((100) * sizeof(char *));  
    for (i = 0; i < 100; i++) 
        row_name[i] = (char*) malloc(10 * sizeof(char));  
    for (i=0; i<100; i++) {
        sprintf(row_name[i],"constr%d",i);
        printf("%s\n", row_name[i]);
      }    
    

Last edited on
Thank you very much.

Andre
Topic archived. No new replies allowed.