這是一個簡單的程序,應該從一個字符串創建一個子字符串,然後它應該返回子字符串作爲可以打印出來的東西。 這實際上是一個練習,只有子字符串函數可以改變。問題是我找不到不會引發各種警告和錯誤的返回類型。返回參數不起作用 - 給我奇怪的錯誤
我應該如何更改返回類型?
static void panic(const char *serror)
{
printf("%s", serror);
exit(1);
}
static void *xmalloc(size_t size)
{
void *ptr;
if (size == 0)
panic("Size is 0!\n");
ptr = malloc(size);
if (!ptr)
panic("No mem left!\n");
return ptr;
}
static char *substring(const char *str, off_t pos, size_t len)
{
char out [len];
int index;
for(index = 0; index < (pos + len); index++)
{
if(index >= pos && index < (pos + len))
{
out[index - pos] = str[index];
}
}
return out;
}
int main(int argc, char **argv)
{
char *foo = "Nicht\n";
char *bar = substring(foo, 2, 3);
printf("%s", bar);
free(bar);
return 0;
}
注意,錯誤消息應被打印到'stderr',而不是標準輸出。然而,像panic()這樣的函數是你的工具包中的一個好工具。 –