任何人都可以帮我将char数组传递给方法,当我尝试它时只复制一个索引值,所以
char c1[]={0x01};
char c2[]={0x02};
char c3[]={0x03};
char *c[3];
c[0] = c1;
c[1] = c2;
c[2] = c3;//if i pass this char array to the below method only c[0] is copied
char* arrrr =[self mountLVparams:NULL :c :code_ward_arr];
//my method being this
-(char *)mountLVparams:(signed char *)initData :(char *)obj :(signed char *)codeWard
答案 0 :(得分:1)
c是指向指针的指针。您的方法签名应该像-(char *)mountLVparams:(signed char *)initData :(char **)obj :(signed char *)codeWard
char c1[]={0x01};
char c2[]={0x02};
char c3[]={0x03};
char *c[3];
c[0] = c1;
c[1] = c2;
c[2] = c3;//if i pass this char array to the below method only c[0] is copied
char* arrrr =[self mountLVparams:NULL :c :code_ward_arr];
-(char *)mountLVparams:(signed char *)initData :(char **)obj :(signed char *)codeWard
{
int i;
for(i=0;i<3;++i)
printf("%d----%c", i,*obj[i]);
}
答案 1 :(得分:1)
通过将数组传递给您的函数然后创建char *
,我有一个解决方案 const char c1[]={0x01};
NSString *s1 = [[NSString alloc] initWithCString:c1 encoding:NSUTF8StringEncoding]; //convert into string
const char c2[]={0x02};
NSString *s2 = [[NSString alloc] initWithCString:c2 encoding:NSUTF8StringEncoding]; //convert into string
const char c3[]={0x03};
NSString *s3 = [[NSString alloc] initWithCString:c3 encoding:NSUTF8StringEncoding]; //convert into string
NSArray *arr = [NSArray arrayWithObjects:s1,s2,s3,nil]; // adding all strings
[s1 release];
[s2 release];
[s3 release];
现在函数就像这样你将传递arr(NSArray):
-(char *)mountLVparams:(signed char *)initData :(NSArray *)arrChars :(signed char *)codeWard
{
int count = [arrChars count];
char *cargs = (char *) malloc(sizeof(char) * (count + 1));
//cargs is a pointer to 4 pointers to char
int i;
for(i = 0; i < count; i++) {
NSString *s = [arrChars objectAtIndex:i];//get a NSString
const char *cstr = [s cStringUsingEncoding:NSUTF8StringEncoding];//get cstring
int len = strlen(cstr);//get its length
char *cstr_copy = (char *) malloc(sizeof(char) * (len + 1));//allocate memory, + 1 for ending '\0'
strcpy(cstr_copy, cstr);//make a copy
cargs[i] = cstr_copy;//put the point in cargs
}
cargs[i] = NULL;
NSLog(@"%c | %c| %c ",cargs[0],cargs[1],cargs[2]);
return cargs;
}
从字符串数组创建char的信用转到@yehnan跟随objective-c nsarray to c array
像这样使用:
char *cs = [self mountLVparams:(your arguments here and pass array here)];
NSLog(@"%c | %c | %c",cs[0],cs[1],cs[2]);
答案 2 :(得分:1)
也许,您可能会寻找以下内容,您可以使用所需内容作为参数传递NSString
对象:
NSString *_string = [NSString stringWithString:@"\x01\x02\x03"];
[self yourMethod:_string];
并在-yourMethod:
- (void)yourMethod:(NSString *)stringWithChars {
char _ch = [stringWithChars characterAtIndex:1]; // it gives back you an unsigned short but in this case you can use this value as char without any problem
NSLog(@"chat at index #1 : %d, %c", _ch, _ch); // or do whatever you'd like to do.
}
答案 3 :(得分:0)
参数c
是指向字符数组的指针。指针将指向数组的第一个地址,因此它默认为c[0]
。
您可以将其作为NSstring传递。 [NSString stringWithFormat:%s,c]
。