tags:

views:

101

answers:

1

HI. This is maybe simple question but I want to create two dimensional array and add it string like in java

string  str = "text" ; 

string [][] array  = new [][] string ;  

array[i][j] = str ; 

But in C there is no string .I tried like this but here strcpy() gives error.It returns to assembly code. I am trying to read line by line from text and split line by space and add them to structure.But first I think that I must add each line and row in array and then making iteration and adding to structures fields.

    static const char filename[] = "student.txt";
FILE *file = fopen ( filename, "r" );
char line [ 128 ]; /* or other suitable maximum line size */
char delims [ ]=" ";
char *result =NULL;
char list[15];
char arra[128][128];
int i=0;
int j=0;

struct {
    char gruppa[10];
    char familiya[20];
    int uchaste;
    struct {
        int firsth;
        int second;
        int third;
        int fourht;
        int fifth;
    } exam;
}student;

for(i=0; i<128; i++)
    for(j=0; j<128; j++) 
        arra[i][j] = '\0';

for(i=0; i<15; i++)
    list[i] = '\0';


if ( file != NULL )
{           
    while ( fgets ( line, sizeof line, file ) != NULL ) 
    {
        result = strtok(line,delims);
                    while (result !=NULL) {



            strcpy(list,("%s",result));
                strcpy(arra[i][j],list); // Here it gives errror 


            j++;
            result = strtok(NULL,delims);
        }
        j=0;
        i++;
    }
    fclose ( file );


}
else
{
    perror ( filename ); 
}


getchar();
return 0;
}
+2  A: 

The strings in C are arrays of char, so your char arra[128][128]; specifies an array of 128 strings, each with length up to 127 characters + the terminating '\0'. If you want 128×128 strings, you need a third dimension.

If you don't mind allocating a fixed amount of memory for every string, then you can just add the third dimension to the existing definition: char array[128][128][max_length_of_string + 1]

(Note that in that case you must ensure that the maximum length is not exceeded, C will not check it for you!)

If you wish to allocate the strings dynamically, you can make the elements char * (i.e. pointers to char): char *array[128][128], but then you must malloc memory for each string (not forgetting the extra char for the trailing '\0' that C strings have). And free all of them when you are done (unless you just exit the program at that point).

Arkku
NO. I want to cerate array that each record will keep string like array[0][0] = str1 , array[0][1]=str2
Meko
@Meko: I edited my post to include an alternative way that allows you to do that. However, if you have `a[128][128][64]`, you *can* do `strcpy(a[0][0], str);` like you are trying to do now, you just need to ensure that the string is at most 63 chars long. Like I said, C strings *are* arrays of characters.
Arkku