问题描述
我有char *类型的象征,我想获得的第二个元素。例如令牌都包含像 4病程长数1405
,我想抓住的第2个字符或4个,并把它变成一个整数。我用strcpy的字符串添加到一个char字符串数组为了抢4个,但我得到了一些错误和IM不太清楚如何解决这些问题。这里是我的code
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;INT搜索(结构ID []数组,字符* TOK);
INT主要(无效)
{ 字符* token2 =1405;
字符*文本[] =的malloc(strlen的(token2)+1);
的strcpy(文字,token2);
INT I,数量;
对于(I = 0; I&下; 4;我+ +)
如果(ⅰ== 1)
{
数=的atoi(token2 [I]); }
的printf(%d个\\ N号);
我得到以下编译错误
GCC structures_arrayof.c
structures_arrayof.c:在函数'主':
structures_arrayof.c:23:20:警告:内建函数'的malloc'不兼容的隐式声明[默认启用]
字符*文本[] =的malloc(strlen的(token2)+1);
^
structures_arrayof.c:23:5:错误:无效初始化
字符*文本[] =的malloc(strlen的(token2)+1);
^
structures_arrayof.c:24:5:警告:传递从兼容的指针类型'的strcpy'的参数1 [默认启用]
的strcpy(文字,token2);
^
5:0在文件从structures_arrayof.c包括:
/usr/include/string.h:129:14:注:应为的char * __restrict__',但参数的类型为字符**
EXTERN的char *的strcpy(字符* __限制__dest,为const char * __限制__src)
要与你在做什么工作....
这应该清除了第一套错误。
的char *文字=的malloc(strlen的(token2)+1);
您是需要一个指向一个字符的字符串。
要做好转换,就需要空终止字符串。
token2 [I + 1] = 0;
然后你可以
数=的atoi(token2 [I]);
i have a token of type char* that i want to get the second element of. For example the tokens all consist of a 4 long course number like 1405
, i want to grab the 2nd character or 4, and turn it into an interger. I use strcpy to add the string into a char string array in order to grab the 4 but i get some errors and im not quite sure how to fix them. here is my code
#include <stdio.h>
#include <string.h>
int search(struct id array[],char* tok);
int main(void)
{
char* token2 = "1405";
char* text[] = malloc(strlen(token2)+1);
strcpy(text,token2);
int i,number;
for(i=0;i<4;i++)
if(i==1)
{
number = atoi(token2[i]); }
printf("%d\n",number);
i get the following compilation errors
gcc structures_arrayof.c
structures_arrayof.c: In function ‘main’:
structures_arrayof.c:23:20: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
char* text[] = malloc(strlen(token2)+1);
^
structures_arrayof.c:23:5: error: invalid initializer
char* text[] = malloc(strlen(token2)+1);
^
structures_arrayof.c:24:5: warning: passing argument 1 of ‘strcpy’ from incompatible pointer type [enabled by default]
strcpy(text,token2);
^
In file included from structures_arrayof.c:5:0:
/usr/include/string.h:129:14: note: expected ‘char * __restrict__’ but argument is of type ‘char **’
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
To work with what you are doing....
This should clear up the first set of errors.
char* text = malloc(strlen(token2)+1);
You are need a pointer to a char string.
To do the the conversion, you need to null terminate the string.
token2[i+1]=0;
Then you can
number = atoi(token2[i]);
这篇关于复制字符串转换成字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!