gpt4 book ai didi

c - 函数有效但也返回 null - C

转载 作者:太空宇宙 更新时间:2023-11-04 06:58:43 25 4
gpt4 key购买 nike

下面的代码旨在获取 URL 路径并将其转换为小写。它完成了这项工作,但它也在小写路径名之后吐出 (null)。据我所知,这与我的 temp 数组需要一个空终止符有关。我已经为它腾出空间并尝试分配它,但我收到以下错误 variable-sized object may not be initialized。我不完全确定如何解决这个问题,因为我还没有培养在 char * 和数组表示法之间完全舒适地切换。如果有人能指出我正确的方向,我将不胜感激!

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

const char* lookup(const char* path);

int main (void)
{
const char* test = lookup("http://WWW.google.COM");

printf("%s", test);

return 0;
}

const char* lookup(const char* path)
{
// this is where I tried to add the null terminator
char temp[strlen(path) + 1];

strcpy(temp, path);

for (int i = 0, n = strlen(path); i < n; i++)
{
if (isalpha(temp[i]))
{
if (isupper(temp[i]))
{
temp[i] = tolower(temp[i]);
}
}
}
printf("%s", temp);
printf("\n");

return 0;
}

最佳答案

数组大小(在本例中为 char 数组)需要在编译时定义。您试图在运行时在 lookup() 函数中定义它。

有两种解决方法:

  • 使用 char 指针和 malloc() 代替固定数组:

    char* temp = malloc (sizeof(path) + 1);
  • 用固定大小声明您的数组(例如,char temp[100]),但请记住您的输入字符串(+1 表示空终止)不能超过这个长度。

您使用第一个选项的完整解决方案(包括其他发帖者指出的修复和删除一些冗余)如下所示:

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

const char* lookup(const char* path);

int main (void)
{
const char* test = lookup("http://WWW.google.COM");

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

free((void*)test);

return 0;
}

const char* lookup(const char* path)
{
// this is where I tried to add the null terminator
char* temp = malloc (strlen(path) + 1);
strcpy(temp, path);

for (int i = 0, n = strlen(path); i < n; i++)
{
if (isupper(temp[i]))
{
temp[i] = tolower(temp[i]);
}
}

return temp;
}

关于c - 函数有效但也返回 null - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40988752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com