Hi people! I'm learning C now and hope someone can help me with the task. I thought I would be able to write strlen function but it doesn't work. Here is the code:
Code:#include "mystrlen.h" int mystrlen(char *s){ int i,k; for(i = 0; s[i] != '\0'; i++){ k++; } return k; }
Code:#include <stdio.h> #include <stdlib.h> #include <string.h> #include "mystrlen.h" int main () { int i; char *p1 = "Use malloc()"; char *p2; if (NULL == (p2 = malloc(mystrlen(p1) + 1))){ printf("Not enough memory!\n"); return 1; } for (i = 0; i <= mystrlen(p1); i++) p2[i] = p1[i]; printf("%s\n",p2); free(p2); return 0; }



LinkBack URL
About LinkBacks



, notice how he loops to i <= strlen, which means he will get the trailing \0 when he does the string copy.