wok*_*uel 2 c runtime function
我试图从传递给getPhoneNumber(char [] str)的字符串中获取电话号码,但由于某种原因,每次运行代码时我都会附加一些随机字符,请我需要帮助.
源代码
#include <stdio.h>
#include <string.h>
char* getPhoneNumber(char str[]);
int main(){
getPhoneNumber("AT+CMGR=5 \n+CMGR: \"REC READ\",\"+9349036332058\",\"samuel\",\"17/03/31,20:44:52+04\"\nHOW THINS fa OK");
return 0;
}
char* getPhoneNumber(char str[]){
char *temp = strchr(str, ',')+2;
const unsigned short len1 = strlen(temp);
printf("value in temp : %s\n\n",temp);
char *strPtr = strchr(temp, '\"');
const unsigned short len2 = strlen(strPtr);
printf("value in strPtr : %s\n\n",strPtr);
int phone_num_len = len1-len2;
char phone_num[phone_num_len];
strncpy(phone_num, temp,phone_num_len);
printf("Phone number : %s",phone_num);
}
Run Code Online (Sandbox Code Playgroud)
我还打印出了temp和strPtr的各个值用于调试目的,但返回的值似乎没问题.程序的输出如下图所示.
你没有留出足够的空间phone_num
.结果,printf
正在读取数组的末尾.这会调用未定义的行为.这就是为什么你在本地运行时看到额外的字符,但它似乎在ideone上工作正常(它似乎对我运行正常).
字符串的空终止字符需要多一个字节.此外,您需要手动添加该空终止符,因为该strncpy
函数不会为您执行此操作,因为在phone_num_len
字节数内没有空终止符temp
.
char phone_num[phone_num_len+1];
strncpy(phone_num, temp,phone_num_len);
phone_num[phone_num_len] = '\0';
Run Code Online (Sandbox Code Playgroud)