gpt4 book ai didi

c - gcc 警告赋值使指针来自整数而不进行强制转换

转载 作者:行者123 更新时间:2023-11-30 16:05:39 26 4
gpt4 key购买 nike

我正在尝试使用数字来制作所有可能的字母组合。 Input NUM由用户给出。这些组合是通过将输入数字拆分为两位数来创建的。 Input获得为char*我正在使用C 。我得到outputSegmenation fault (core dumped) ,由于警告而猜测。
substr是我自己的功能。 sample inputoutput

input: 11112
output:
AAAAB
AAAL
AAKB
AKAB
AKL
KAAB
KAL
KKB

我的CODE

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

char* substr(char* str,int l,int n)
{
char* c;
int len = n-l;
while(l<n)
{
*c = *(str+l);
l++;
c++;
}
*c='\0';
return c-len;
}


int printAlpha(char* str, char* word)
{
char *sub;
char* ch;
int n = strlen(str);
if(n == 0)
{
printf("%s",word);
}
else
{

sub = substr(str,0,1);
int num = atoi(sub);
str = substr(str,1,n);
ch = 'A'+(num-1);
printAlpha(str, strcat(word, ch));
sub = substr(str,0,2);
num = atoi(sub);
if(strlen(str)>=2 && num <= 26)
{
str = substr(str,2,n);
ch = 'A'+(num-1);
printAlpha( str, strcat(word, ch) );
}
}
return 0;
}


int main()
{
char* str;
char* word = '\0';
scanf("%s",str);
printAlpha(str,word);

return 0;
}

提前致谢。

最佳答案

正如评论者所说,您需要在 c 中动态分配内存。

在 c 中,如果你需要存储类似字符数组的内容,你有 2 个基本场景:

  1. 在编译之前您就知道数组将包含多少个元素,然后就可以使用

    字符字[字母数]

只要您不需要存储更多字母,这就会起作用,在其他情况下就会出现问题

  • 编译前你不知道数组有多大

    例如,当您正在做长度可验证的事情时。想象一下将用户输入存储到字符数组中。你应该如何制作数组?如果您将其设置为 100 个字符,并且用户输入 101,那么您将遇到段错误或丢失他在第 100 个字符之后输入的所有内容

  • 你也可以通过使数组变大来解决这个问题,但是如果输入很短,你会浪费大量内存,而且你仍然会遇到一个问题,如果你需要比你选择的大小多 1 个字符,它将无法工作.

    在这里,您必须使用动态内存分配,使用诸如 element_ptr* =malloc(numOfElements*sizeof(element)); 之类的函数来在运行时请求内存。

    malloc 的作用是返回一个指向您请求的内存地址的指针

    当你不再需要内存时,你可以调用free(element_ptr);这将再次释放内存,否则它将保持阻塞状态。

    最好在手册页中阅读有关 malloc 的内容

    关于c - gcc 警告赋值使指针来自整数而不进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60224445/

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