我一直在编写一个用于在每个两个换行符之间提取信息的函数。将char数组'data'复制到'info'数组的元素时遇到一个问题。
#include <stdio.h>
#include <string.h>
void query_db();
char buffer[100]="+HTTPREAD:86\nUdara\nNO\n+94123456789\nOK";
volatile int buffer_pointer;
char info[3][20];
int main()
{
query_db();
return 0;
}
void query_db(){
unsigned char j=0,start,end,amount;
char data[20];
buffer_pointer = 0;
while( buffer_pointer < strlen(buffer)){
if(buffer[buffer_pointer] == 10){
if(j==0){
start = buffer_pointer+1;
printf("headstart = %u\n",start);
}
else{
printf("\n%u start = %u\n",j,start);
end = buffer_pointer;
amount = end - start;
strncpy(data, buffer+start,amount);
memcpy(info[j-1],data,strlen(data));//need help in this line
printf("data = %s\n",info[j-1][20]);
memset(data,0,20);
start = end+1;
printf("%u end = %u\n",j,end);
}
j++;
}
buffer_pointer++;
}
}
当我执行以上代码时,它会给出以下输出,而不是我的预期。
headstart = 13
1 start = 13
data = (null)
1 end = 18
2 start = 19
data = (null)
2 end = 21
3 start = 22
data = (null)
3 end = 34
首选输出:
headstart = 13
1 start = 13
data = Udara
1 end = 18
2 start = 19
data = NO
2 end = 21
3 start = 22
data = +94123456789
3 end = 34
答案 0 :(得分:2)
输出错误的问题在这里:
printf("data = %s\n",info[j-1][20]);
您使用"%s"
格式打印字符串,但是info[j-1][20]
是单个char
。而且这也超出了范围。
您可能打算使用info[j-1]
。
答案 1 :(得分:1)
memcpy((char *)&info[j-1],data,strlen(data));