-1

I want to assign a value to my char * like that:

char *text;
struct node *ptr = head;

//start from the beginning
while(ptr != NULL)
{        
   text = ptr->key + ";" + ptr->data + ";\n";
   ptr = ptr->next;
   fprinft(f, text);
}

The key value is a char[] and the data value an int.

I get the following error:

Error: invalid operands to binary + (have ‘int’ and ‘char *’) text = ptr->key + ";" + ptr->data + ";\n";

Does anyone know how to fix that problem?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
mafioso
  • 1,630
  • 4
  • 25
  • 45

3 Answers3

2

As the concatenation of ptr->key, ";", ptr->data, ";\n" does not need to exist after the loop, just print it to the file. @user3386109

// Not needed
// char *text;

struct node *ptr = head;

while(ptr != NULL) {
   //           v--v----- printf specifiers for a pointer to a string and int 
   fprinft(f, "%s;%d;\n", ptr->key, ptr->data);
   ptr = ptr->next;
}
Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
-1

You need to malloc() it. This is because strings in c are stored in memory as arrays of chars but if you don't malloc() it and initialize a string as

char* string = "this is a string";

it will be stored in read only memory.

What you can do is either malloc() it or store it as an array.

Hope this helps!

Heatblast016
  • 8
  • 1
  • 3
-2

First you would need to allocate memory for your *text, and then use strcat function for adding these strings together...

#include <string.h>
void function(...) {
  char* text = (char*)malloc(sizeof(char) * 100); // for 99 chars + NULL 
  text[0] == 0;
  struct node* ptr = head;

  //start from the beginning
   while(ptr != NULL)
   {
     if(text[0] == 0)  //you cant strcat empty string, only existing one
       strcpy(text, ptr->key);
     else
       strcat(text, ptr->key);
     strcat(text, ";");
     strcat(text, ptr->data);
     strcat(text, ";\n");
     ptr = ptr->next;
     fprinft(f, text);
  }
}

This code assumes both ptr->key and ptr->data are char arrays (strings), if they are not, you need to convert them to strings : look into itoa function...

Rorschach
  • 734
  • 2
  • 7
  • 22
  • Of course, I was thinking of `itoa`. Small confusion. – Rorschach Oct 11 '16 at 21:02
  • 1
    Where did you get the "you cant strcat empty string, only existing one" from? – EOF Oct 11 '16 at 21:14
  • I get the following error executing your code: /tmp/ccu6S8bc.o: In function `main': WriteInFile.c:(.text+0x197): undefined reference to `itoa' WriteInFile.c:(.text+0x20f): undefined reference to `fprinft' – mafioso Oct 11 '16 at 21:17
  • 1
    @mafioso Because it's `fprintf` and if `key` is `char*` while `data` is an `int` you only have to write `fprintf(f, "%s;%d;\n", ptr->key, ptr->data);` – Bob__ Oct 11 '16 at 21:36
  • `text[0] == 0; strcat(text, ptr->key);` is just fine. `text[0] == 0; strncat(text, ptr->key, 100);` is even better. – chux - Reinstate Monica Oct 11 '16 at 21:58