0

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);
1
  • 7
    table[i][5+(i/2)] = *ptr; is correct. The segmentation fault is because i exceeds the table dimensions. Commented Jun 26, 2013 at 7:33

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so you purpose me to increase the dimensions of the array??
@dali1985 No! You should make sure that i doesn't exceed the dimensions. This indicates that your logic is not good, you should reconsider the loop and perform some checks before inserting a value to the table.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.