程序,在函数中强制转换警告,返回与输入数字相同数量的x

  • 本文关键字:数字 返回 函数 程序 警告 转换 c
  • 更新时间 :
  • 英文 :


我一直致力于创建一个C程序,给定一个数字序列(作为字符数组提供),该程序返回与输入包含的数字数量相同的X(例如input: "1234"—>输出:"XXXX"

我写的代码是:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* getPlaceholder(char * word);
int main(){
char * myWords []={"111","22222","1113445","9"};
char ** mywords_pointer=myWords;
/*We will apply the function getPlaceholder to each of the components of the myWords array */
for (int indx=0; indx<3; indx++){
char *currentWord=*(mywords_pointer+indx);
const char *placeholder;
printf("Calling functionn");
placeholder=getPlaceholder(currentWord);
printf("The placeholder for %s is: %sn",currentWord, placeholder);
}
return 0;
}

//getPlaceholder gets a number as a string and outputs as many Xs as digits the imput number has.  
const char* getPlaceholder(char * number){
char *ptr; 
long wordAsNumb=strtol(number,&ptr,10);/* in order to later be able to count the number of digits the input 'number' has*/
char *currentPlaceholder='';//this variable is initialised and later we will later be added new Xs in case the input number has more than one digit. 

"222"--> 222
''
.X '
while (wordAsNumb>1){
size_t len=strlen(currentPlaceholder); //this is the variable which will contain the placeholder (Xs) corresponding to the input number
char *output_string=malloc(len+2); /* adds two new characters to fit a new X (to increase the number of digits the input number has) and the "" */

strcpy(output_string,currentPlaceholder);
output_string[len]='X';
output_string[len+1]='';
/* in order to copy the currentPlaceholder value to 'output_string'. Then we add the two nex characters in the array*/
printf("String output is now %sn ",output_string);
strcpy(currentPlaceholder,output_string);
free (output_string);
wordAsNumb/=10;
}
const char* finalPlaceholder=currentPlaceholder;
return finalPlaceholder;
}

然而,我偶然发现了警告:

initialization makes pointer from integer without a cast [-Wint-conversion]

行:

 char *output_string='X';

有什么想法到底是错的吗?

多谢

文字字符常量(在单引号中)的类型为int

char output_char = 'X' ;

char* output_string = "X" ;

,这取决于所需的语义。然而,这里所需的语义是不明确的。不清楚初始化甚至指针本身是为了什么,因为它是未使用的。后来的

char *output_string=malloc(len+2);

遮蔽它并使其不可访问。实际上,你可以直接删除整个声明。

老实说,剩下的代码没有什么意义,而且有严重的错误。它会崩溃:

Program received signal SIGSEGV, Segmentation fault.
strlen () at ../sysdeps/x86_64/strlen.S:106

但那是另一个问题。

最新更新