[英]How to use malloc in this situation?
我是C的新手,所以請忍受...
我有一個函數來計算名為char strLength
的字符串中的char strLength
,但是我必須創建一個函數,該函數使用此函數來計算所傳遞的字符串中的字符數,為NULL終止符分配帶有空格的新字符串,並復制該字符串然后返回副本。
這是我所擁有的:
字符計數器
int strLength(char* toCount)
{
int count = 0;
while(*toCount != '\0')
{
count++;
toCount++;
}
return count;
}
這是搶手功能的開始
char* strCopy(char *s)
{
int length = strLength(s);
}
由於您在努力使用malloc
,因此,下一行應如下所示:
char* strCopy(char *s)
{
int length = strLength(s);
char *res = malloc(length+1);
// Copy s into res; stop when you reach '\0'
...
return res;
}
您想要strdup
。 但是,由於我懷疑這是一個學習練習:
char *strCopy(const char *src)
{
size_t l = strlen(src) + 1;
char *r = malloc(l);
if (r)
memcpy(r, src, l);
return r;
}
如果您想知道如何自己復制字符串,可以將memcpy
替換為以下內容:
char *dst = r;
while (*src)
*dst++ = *src++;
*dst = 0;
但是我建議使用庫函數:如果不是strdup
,則為malloc
+ memcpy
。
您可以使用strdup()clib調用。
您可以這樣寫:
char* strCopy(char *s) { int length = strLength(s); char *rc = (char *)malloc(length + 1); return rc? strcpy(rc, s) : NULL; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.