这是我的代码。该代码应该从用户获取字符串并输出字符串的长度。我之所以使用指针,是因为我试图在不得不将其移动到函数之前使代码工作。
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
//init variables
char *userInput = malloc(sizeof(20)) ;
int stringLength;
//input
printf("Hello. Please enter a string: n");
fgets(userInput,20,stdin);
//Calculations & Function Calls
size_t stringLength = strlen(userInput);
//output
printf("This is your input:, %s n", userInput);
printf("Length: %d n", stringLength);
return 0;
}
使用strlen((时,我的编译器给我带来了转换错误。我已经尝试将铸造铸造到INT和其他方法,但没有运气。我正在使用GCC编译器,如果它更改了任何内容。
感谢您的帮助!
您正在声明变量stringLength
两次:
int main()
{
//init variables
char *userInput = malloc(20); // see explications below
int stringLength; // <<<<<< here
//input
printf("Hello. Please enter a string: n");
fgets(userInput,20,stdin);
//Calculations & Function Calls
size_t stringLength = strlen(userInput); // <<<<<< and here
//output
printf("This is your input:, %s n", userInput);
printf("Length: %d n", stringLength);
return 0;
}
替换
size_t stringLength = strlen(userInput);
stringLength = strlen(userInput);
和事先声明
size_t stringLength;
而不是
int stringLength;
或只是删除int stringLength;
和malloc(sizeof(20))
应为malloc(20)
。您想分配20个字节。 sizeof(20)
实际上是int
的大小,很可能取决于平台。
c仅允许一个变量的一种类型声明。当您尝试再次声明的代码时,已经声明了stringLength
标识符。因此您的代码将是
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
//init variables
char *userInput = malloc(sizeof(20)) ;
unsigned int stringLength;
//input
printf("Hello. Please enter a string: n");
fgets(userInput,20,stdin);
//Calculations & Function Calls
stringLength = strlen(userInput);
//output
printf("This is your input:, %s n", userInput);
printf("Length: %u n", stringLength);
return 0;
}
您的程序尝试声明变量stringLength
两次。
一次
int stringLength;
和第二次为:
size_t stringLength = strlen(userInput);
C语言不允许使用。编译器可以捕获它。
还请确保您为字符串分配足够的内存。这可以给您带来运行的时间问题,因为您将覆盖字符串的内存更长,然后长度分配的内存。sizeof(20)
是4
。您的目的是分配20
字节。
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
//init variables
char *userInput = malloc(20 * sizeof(char)) ;
size_t stringLength;
//input
printf("Hello. Please enter a string: n");
fgets(userInput,20,stdin);
//Calculations & Function Calls
stringLength = strlen(userInput);
//output
printf("This is your input: %sand it has length: %zu. The sizeof(20) is %zu n", userInput, stringLength, sizeof(20));
return 0;
}
输出:
12345
Hello. Please enter a string:
This is your input: 12345
and it has length: 6. The sizeof(20) is 4