简体   繁体   English

将NSString转换为c字符串时,字符串复制函数不返回值strcpy

[英]String copy function returns no value strcpy while converting NSString to c string

sipurl and regurl are NSString which I get from UItextField sipurlregurl是我从UItextField获得的NSString

    const char *sipAddr = [sipUrl cStringUsingEncoding:NSUTF8StringEncoding];
    const char *regAddr = [regUrl cStringUsingEncoding:NSUTF8StringEncoding];
    const char *uname = [orgUsername cStringUsingEncoding:NSUTF8StringEncoding];
    const char *pword = [password cStringUsingEncoding:NSUTF8StringEncoding];
    //const char *pword = [password UTF8String];
    const char *realm = [realmStr cStringUsingEncoding:NSUTF8StringEncoding];

    //char *sipAddrArr=strdup(sipAddr);
    //char *regAddrArr=strdup(regAddr);
    //char *unamearr=strdup(uname);
    //char *pwordarrnew = strdup(pword);

    char sipAddrArr[[sipUrl length]];
    strcpy(sipAddrArr,sipAddr);

    char regAddrArr[[regUrl length]];
    strcpy(regAddrArr,regAddr);

    char unamearr[[orgUsername length]] ;
    strcpy(unamearr, uname);

    char pwordarrnew[[password length]];
    strcpy(pwordarrnew,pword);

    char realmchr[[realmStr length]];
    strcpy(realmchr,realm);
    char pwordarr1[] = {"10000"};
    printf("\nPassword value sent: %s",pword);
    printf("\nPassword value sent: %s",pwordarr1);

pword has value while trying to copy constant char to char I use strcpy function it returns no value for pword. pword在尝试将常量char复制到char时有价值我使用strcpy函数它不返回pword的值。 The same code works fine when testing in simulator but doesn't work when connected to iOS phone. 在模拟器中测试时,相同的代码工作正常但在连接到iOS手机时不起作用。

This may or may not be the cause of your problem, but it is an error in your code: 这可能是您的问题的原因,也可能不是,但在您的代码中是错误的:

You are taking an NSString , converting it into a UTF8 C-string, and then copying the C-string into a C-array sized according to the length of the NSString . 您正在使用NSString ,将其转换为UTF8 C字符串,然后将C字符串复制到根据NSString长度调整大小的C数组中。 This is wrong, the NSString and its UTF8 translation can be different lengths. 这是错误的, NSString及其UTF8转换可以是不同的长度。 You need to determine the length of the UTF8 string and allow for the end-of-string marker. 您需要确定UTF8字符串的长度并允许字符串结束标记。 For example: 例如:

char sipAddrArr[strlen(sipAddr)+1];
strcpy(sipAddrArr,sipAddr);

and similarly for the other arrays. 并且类似地用于其他阵列。

HTH HTH

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

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