分配使得指针从整数,未投 [英] Assignment makes pointer from integer without cast
问题描述
这是一个Java的背景,我学习C的到来,但我觉得那些模糊的编译器错误消息越来越沮丧。这里是我的code:
Coming from a Java background I'm learning C, but I find those vague compiler error messages increasingly frustrating. Here's my code:
/*
* PURPOSE
* Do case-insensetive string comparison.
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int compareString(char cString1[], char cString2[]);
char strToLower(char cString[]);
int main() {
// Declarations
char cString1[50], cString2[50];
int isEqual;
// Input
puts("Enter string 1: ");
gets(cString1);
puts("Enter string 2: ");
gets(cString2);
// Call
isEqual = compareString(cString1, cString2);
if (isEqual == 0)
printf("Equal!\n");
else
printf("Not equal!\n");
return 0;
}
// WATCH OUT
// This method *will* modify its input arrays.
int compareString(char cString1[], char cString2[]) {
// To lowercase
cString1 = strToLower(cString1);
cString2 = strToLower(cString2);
// Do regular strcmp
return strcmp(cString1, cString2);
}
// WATCH OUT
// This method *will* modify its input arrays.
char strToLower(char cString[]) {
// Declarations
int iTeller;
for (iTeller = 0; cString[iTeller] != '\0'; iTeller++)
cString[iTeller] = (char)tolower(cString[iTeller]);
return cString;
}
这会产生两个警告。
- 赋值时将整数指针,未作投
- cString1 =用strtolower(cString1);
- cString2 =用strtolower(cString2);
- 返回CString的;
有人能解释这些警告?
推荐答案
C字符串不是像Java字符串东西。他们基本上是字符数组。
C strings are not anything like Java strings. They're essentially arrays of characters.
您所得到的错误,因为用strtolower返回一个char。一个char是整数C.你是分配给它到一个char []这是一个指针的形式。因此,转换为指针的整数。
You are getting the error because strToLower returns a char. A char is a form of integer in C. You are assigning it into a char[] which is a pointer. Hence "converting integer to pointer".
您用strtolower使得其全部到位的变化,没有理由为它返回任何东西,特别是没有一个字符。你应该回归无效,或一个char *。
Your strToLower makes all its changes in place, there is no reason for it to return anything, especially not a char. You should "return" void, or a char*.
在调用用strtolower,也没有必要转让,你基本上是刚好路过的存储器地址cString1。
On the call to strToLower, there is also no need for assignment, you are essentially just passing the memory address for cString1.
在我的经验,在C字符串是来学习的人从Java / C#背景回来C.人们可以使用的内存分配相处(因为即便在Java中你经常分配数组)是最难的部分。如果你的最终目标是C ++而不是C,你可能preFER少关注C字符串,请确保您了解的基础知识,只是使用C ++字符串从STL。
In my experience, Strings in C are the hardest part to learn for anyone coming from Java/C# background back to C. People can get along with memory allocation (since even in Java you often allocate arrays). If your eventual goal is C++ and not C, you may prefer to focus less on C strings, make sure you understand the basics, and just use the C++ string from STL.
这篇关于分配使得指针从整数,未投的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!