小编jho*_*nna的帖子

为什么我不能strcpy?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main() {
   const char* hello = "Hello, World!";
   char *str = malloc(14 * sizeof(char));

   for (int i = 0; i < 14; i++) {
      strcpy(str[i],hello[i]);
   }
   str[14]='\0';

   printf("%s\n", str);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译警告:

warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast [-Wint-conversion]   
note: expected 'char *' but argument is of type 'char'   
warning: passing argument 2 of 'strcpy' makes pointer from integer without a cast [-Wint-conversion]

str也是一个指针和你好,发生了什么事?

c pointers strcpy

5
推荐指数
1
解决办法
454
查看次数

便携性无效**

当我发现((void**)&ptr)时,我正在阅读http://c-faq.com/ptrs/genericpp.html ; "不便携",这是正确的吗?因为它似乎工作......

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void *wrapper_free(void **p){

     if(p){
       free(*p);
       *p=NULL;
     }

     return NULL;
}

int main() {

    int *ptr=malloc(sizeof(int));
    *ptr=20;

     printf("%d\n",ptr);

     wrapper_free((void **)&ptr); //Not portably?

     printf("%d",ptr);

     return 0;
}
Run Code Online (Sandbox Code Playgroud)

是((void**)&ptr); 便携?

c pointers

0
推荐指数
1
解决办法
83
查看次数

为什么strcpy返回char*而不是char

很多字符串函数返回一个指针,但是返回指向目标和返回目标的指针的优点是什么?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *sstrcpy ( char *destination, const char *source ){ //return a pointer to destination

    while ((*destination++ = *source++));
    *destination='\0';

return destination;
}

char sstrcpy2 ( char *destination, const char *source ){ //return destination

    while ((*destination++ = *source++));
    *destination='\0';

    return *destination;
}

int main(void){
    char source[] = "Well done is better than well said";
    char destination[40];

    sstrcpy ( destination, source );
    printf ( "%s\n", destination);



    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c

0
推荐指数
1
解决办法
313
查看次数

指针减法strlen

我不明白sstrlen的最后一行,return t-str;.
str指向"my string"t指出\0为什么它有效?

#include <stdio.h>

size_t sstrlen(char *str){
    char *t = str;
    for(;*t != '\0';t++);
    return t-str; // how does it work?
}

int main()
{
    char *str = "my string";
    printf("%zu",sstrlen(str));     
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c

0
推荐指数
1
解决办法
116
查看次数

标签 统计

c ×4

pointers ×2

strcpy ×1