0
votes

I have the following code which gets some char tokens with strtok and it keeps these tokens one by one in a table and finally print these tokens. My error is in TABLE line:

error: invalid conversion from 'char* to 'char''

Something I misunderstood about the pointers and characters and I do not know how to write the TABLE line ((which I want to have the following format)). I tried something like

table[i][5+(i/2)] = *ptr;

but I had segmentation fault.

i = 0;
int offset = 5;
char* ptr;
ptr = strtok(buff,"do something");
char table[1][10];       
while (ptr != NULL)
 {
  if (i == 0)
     strcat(machine, ptr);
  if (i == 2)
     strcat(number, ptr);
  if (i == 4)
     strcat(hr, ptr); 
  if (i == 6)
     strcat(dw, ptr); 
  if (i == 8)
     strcat(vcc, ptr);
  ptr = strtok(NULL,"do something");
  table[i][5+(i/2)] = ptr;     
  i++;
 }
printf("Final: %s, %s, %s, %s, %s\n", machine, number, hr, dw, vcc);
2
table[i][5+(i/2)] = *ptr; is correct. The segmentation fault is because i exceeds the table dimensions.Maroun

2 Answers

3
votes

table[i][5+(i/2)] = ptr; is wrong because you are trying to assign address instead of value.

table[i][5+(i/2)] = *ptr; is correct. It will give the value at the ptr.

Segmentation fault is because of i. it is referring an address which is out of array boundary.

0
votes

You have missing some variables, and memory setup's. the variable machine should allocate enough memory, to store your strings in it. same for number, hr, dww, and vcc. Then, your table variable has coded, that only one (1) entry can exists in it - in other words: your table[1] is invalid, because it has not enough room, to "add" pointers to it. The array after table[1] - also the [10] ( table[1][10] ) indicates each table item (here, only one) that have it 10 bytes in length/size. So, you just write a "char" array, which can contain ten(10) characters. Which give a "static" literal/string.

As this, you can be lucky, if you don't get a system fault. But table seems be irrelevant, because your last code line, so far i can see this, only print number, hr, dww, and vcc on screen.

But this is not the mistake alone. Before all this code, you should get a crash at

char *ptr;
ptr = strtok(buff,"do something");

because you don't allocate memory for ptr, one line above.