简体   繁体   English

数组中的字符指针值

[英]char pointer value in array

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.我有以下代码,它使用 strtok 获取一些字符标记,并将这些标记一个一个地保存在表中,最后打印这些标记。 My error is in TABLE line:我的错误在 TABLE 行:

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)).我对指针和字符有一些误解,我不知道如何编写 TABLE 行((我希望采用以下格式))。 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);

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 . 它将给出ptr处的值。

Segmentation fault is because of i . 分割错误是由于i it is referring an address which is out of array boundary. 它是指超出数组边界的地址。

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 . numberhrdwwvcc 也是如此 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.然后,您的table变量已编码,其中只能存在一 (1) 个条目 - 换句话说:您的 table[1] 无效,因为它没有足够的空间来“添加”指向它的指针。 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. table[1] 之后的数组 - 也是 [10] ( table[1][10] )表示每个表项(这里只有一个)的长度/大小为 10 个字节。 So, you just write a "char" array, which can contain ten(10) characters.因此,您只需编写一个“char”数组,它可以包含十(10)个字符。 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.但是 table 似乎无关紧要,因为您的最后一行代码,到目前为止我可以看到这一点,只在屏幕上打印numberhrdwwvcc

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.因为你没有为 ptr 分配内存,上面一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM