BaRud
BaRud

Reputation: 3230

copy char to char array

I am trying to copy a "string" to array of strings in C:

const gchar  *strAuth, *strEditor, *strTitle; 
gchar *strings[18][150];
strcpy(strings[0],strAuth);

while compiling, gcc is giving warning: warning: passing argument 1 of ‘strcpy’ from incompatible pointer type [enabled by default]

Possibly, due to this fault of mine, the check and print in the later part of the code

  g_print("%s", strings[0]);
  int i=0;
  while (i <= 18) {
    if (strlen(strings[i]) != 0) {
      g_string_append_printf(tstring, "\t%s=\"%s\",\n",
      keyword[i], strings[i]);
      i++;
    } 
  }

is also not working (it is printing empty strings as well). C is not my language, so kindly help

NB:thecked this and this, but failed to help myself NB: gchar "Corresponds to the standard C char type." in glib

Upvotes: 2

Views: 2217

Answers (2)

Terminality
Terminality

Reputation: 819

The most immediate fix (without suggesting a totally different approach) requires a couple of fixes.

The thing about the warning is that you are creating an array of 18x150 pointers, but I guess you want 18 strings of length 150, so the definition should be:

gchar strings[18][150];  // 18 strings of 150 chars

The way your code looks, you would probably also assume to be zero initialized (empty strings if not filled) so you might add:

gchar strings[18][150]= { "", };  // 18 empty strings of 150 chars

.

Another (more severe) error in your code is that your loop is running [0...18]. But your list of strings is only gchar *strings[18][150]; so it should run [0..17]. Also the increment of I should also happen when length strings[i] is zero (otherwise you will get an infinite loop, never reaching the end if one string is empty).

  while (i < 18) {  // <-- FIX 
    if (strlen(strings[i]) != 0) {
      g_string_append_printf(tstring, "\t%s=\"%s\",\n",
      keyword[i], strings[i]);
    } 
    i++;  // <-- FIX 
  }

Upvotes: 1

Lundin
Lundin

Reputation: 215330

You have not declared an array of strings. You have declared a 2D array of 18x150 pointers to char.

Therefore you get a warning: you are trying to copy a string, into an array of pointers.

An array of strings would have been char strings [18][150].

Upvotes: 4

Related Questions