I’m having a small problem trying to malloc this struct.
Here is the code for the structure:
typedef struct stats {
int strength;
int wisdom;
int agility;
} stats;
typedef struct inventory {
int n_items;
char **wepons;
char **armor;
char **potions;
char **special;
} inventory;
typedef struct rooms {
int n_monsters;
int visited;
struct rooms *nentry;
struct rooms *sentry;
struct rooms *wentry;
struct rooms *eentry;
struct monster *monsters;
} rooms;
typedef struct monster {
int difficulty;
char *name;
char *type;
int hp;
} monster;
typedef struct dungeon {
char *name;
int n_rooms;
rooms *rm;
} dungeon;
typedef struct player {
int maxhealth;
int curhealth;
int mana;
char *class;
char *condition;
stats stats;
rooms c_room;
} player;
typedef struct game_structure {
player p1;
dungeon d;
} game_structure;
And here is the code I’m having a problem with:
dungeon d1 = (dungeon) malloc(sizeof(dungeon));
It gives me the error «error: conversion to non-scalar type requested»
Can someone help me understand why this is?
hlovdal
25.6k10 gold badges93 silver badges162 bronze badges
asked Mar 5, 2012 at 3:34
You can’t cast anything to a structure type. What I presume you meant to write is:
dungeon *d1 = (dungeon *)malloc(sizeof(dungeon));
But please don’t cast the return value of malloc()
in a C program.
dungeon *d1 = malloc(sizeof(dungeon));
Will work just fine and won’t hide #include
bugs from you.
answered Mar 5, 2012 at 3:37
Carl NorumCarl Norum
216k38 gold badges422 silver badges468 bronze badges
5
malloc
returns a pointer, so probably what you want is the following:
dungeon* d1 = malloc(sizeof(dungeon));
Here is what malloc looks like:
void *malloc( size_t size );
As you can see it return void*
, however you shouldn’t cast the return value.
answered Mar 5, 2012 at 3:38
Jesse GoodJesse Good
50k14 gold badges120 silver badges166 bronze badges
The memory assigned by malloc
must be stored in a pointer to an object, not in the object itself:
dungeon *d1 = malloc(sizeof(dungeon));
answered Mar 5, 2012 at 3:37
Adam LissAdam Liss
47k12 gold badges107 silver badges147 bronze badges
struct key new_node = (struct key) calloc(1, sizeof(struct key));
calloc
returns a pointer value (void *
), which you are trying to convert and assign to an aggregate (IOW, non-scalar) type (struct key
). To fix this, change the type of new_node
to struct key *
and rewrite your allocation as follows:
struct key *new_node = calloc(1, sizeof *new_node);
Two things to note. First of all, ditch the cast expression. malloc
, calloc
, and realloc
all return void *
, which can be assigned to any object pointer type without need for a cast1. In fact, the presence of a cast can potentially mask an error if you forget to include stdlib.h
or otherwise don’t have a declaration for malloc
in scope2.
Secondly, note that I use the expression *new_node
as the argument to sizeof
, rather than (struct key)
. sizeof
doesn’t evaluate it’s operator (unless it’s a variable array type, which this isn’t); it just computes the type of the expression. Since the type of the expression *new_node
is struct key
, sizeof
will return the correct number of bytes to store that object. It can save some maintenance headaches if your code is structured like
T *foo;
... // more than a few lines of code
foo = malloc(sizeof (T))
and you change the type of foo
in the declaration, but forget to update the malloc
call.
Also, it’s not clear what you’re trying to accomplish with your typedefs and struct definitions. The code
typedef struct value_t value;
struct value{
void* x;
int y;
value* next;
value* prev;
};
isn’t doing what you think it is. You’re creating a typedef name value
which is a synonym for an as-yet-undefined type struct value_t
. This value
type is different from the struct value
type you create later (typedef names and struct tags live in different namespaces). Rewrite your structs to follow this model:
struct value_t {
void *x;
int y;
struct value_t *next;
struct value_t *prev;
};
typedef struct value_t value;
Also, life will be easier if you write your declarations so that the *
is associated with the declarator, not the type specifier3. A declaration like T* p
is parsed as though it were written T (*p)
. This will save you the embarrassment of writing int* a, b;
and expecting both a
and b
to be pointers (b
is just a regular int
).
1 — This is one area where C and C++ differ; C++ does not allow implicit conversions between void *
and other object pointer types, so if you compile this as C++ code, you’ll get an error at compile time. Also, before the 1989 standard was adopted, the *alloc
functions returned char *
, so in those days a cast was required if you were assigning to a different pointer type. This should only be an issue if you’re working on a very old system.
2 — Up until the 1999 standard, if the compiler saw a function call without a preceding declaration, it assumed the function returned an int
(which is why you still occasionally see examples like
main()
{
...
}
in some tutorials; main
is implicitly typed to return int
. As of C99, this is no longer allowed). So if you forget to include stdlib.h
and call calloc
(and you’re not compiling as C99), the compiler will assume the function returns an int
and generate the machine code accordingly. If you leave the cast off, the compiler will issue a diagnostic to the effect that you’re trying to assign an int
value to a pointer, which is not allowed. If you leave the cast in, the code will compile but the pointer value may be munged at runtime (conversions of pointers to int
and back to pointers again is not guaranteed to be meaningful).
3 — There are some rare instances, limited to C++, where the T* p
style can make code a little more clear, but in general you’re better off following the T *p
style. Yes, that’s a personal opinion, but one that’s backed up by a non-trivial amount of experience.
Содержание
- GCC Debugging/g++/Errors
- Contents
- abstract declarator ‘TYPE’ used as declaration [ edit | edit source ]
- call of overloaded ‘FUNCTION’ is ambiguous [ edit | edit source ]
- ‘VARIABLE’ cannot appear in a constant-expression [ edit | edit source ]
- ‘VARIABLE’ cannot be used as a function [ edit | edit source ]
- conversion from ‘TYPE’ to non-scalar type ‘TYPE’ requested [ edit | edit source ]
- could not convert ‘STATEMENT’ to ‘bool’ [ edit | edit source ]
- declaration of ‘FUNCTION’ outside of class is not definition [ edit | edit source ]
- declaration of ‘VARIABLE’ shadows a parameter [ edit | edit source ]
- ‘TYPE’ does not name a type [ edit | edit source ]
- expected ‘TOKEN’ before ‘TOKEN’ token [ edit | edit source ]
- expected primary-expression before ‘TOKEN’ [ edit | edit source ]
- expected unqualified-id before [ edit | edit source ]
- incompatible types in assignment of ‘TYPE’ to ‘TYPE’ [ edit | edit source ]
- invalid conversion from ‘TYPE’ to ‘TYPE’ [ edit | edit source ]
- invalid operands of types ‘TYPE’ and ‘TYPE’ to binary ‘FUNCTION’ [ edit | edit source ]
- invalid use of template-name [ edit | edit source ]
- is not a member of [ edit | edit source ]
- ‘TYPE’ is not a type [ edit | edit source ]
- ‘CLASS_MEMBER’ is private within this context [ edit | edit source ]
GCC Debugging/g++/Errors
Contents
abstract declarator ‘TYPE’ used as declaration [ edit | edit source ]
- Message found in GCC version 4.5.1
- often grouped together with:
- member ‘DATA_MEMBER’ with constructor not allowed in anonymous aggregate
- member ‘DATA_MEMBER’ with destructor not allowed in anonymous aggregate
- member ‘DATA_MEMBER’ with copy assignment operator not allowed in anonymous aggregate
- often grouped together with:
- a class or struct is missing a name:
- a header file has a class or struct with a name already used inside ifndef, define statements
call of overloaded ‘FUNCTION’ is ambiguous [ edit | edit source ]
‘VARIABLE’ cannot appear in a constant-expression [ edit | edit source ]
‘VARIABLE’ cannot be used as a function [ edit | edit source ]
- Message found in GCC version 4.5.1
- make sure the variable name does not have an underscore in it (compiler weirdness)
- you’re using the same name for a variable name and a function inside a function definition
conversion from ‘TYPE’ to non-scalar type ‘TYPE’ requested [ edit | edit source ]
- Message found in GCC version 4.5.1
- type conversion error, look for missing «::» syntax or missing parenthesis
- possibly a casting error
- a class member function returns a value that does not match the function’s declared return type
could not convert ‘STATEMENT’ to ‘bool’ [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- you a mistyped comparison operator (e.g., using: «=» instead of «==»)
- you used an incorrect return type for the called function’s definition
- you’re using an invalid argument for a conditional statement
declaration of ‘FUNCTION’ outside of class is not definition [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- try using ‘=’ to initialize a value instead of parenthesis
- you used a semicolon or comma between a constructor and an initializer list instead of a colon
- you left a semicolon before the body of a function definition
declaration of ‘VARIABLE’ shadows a parameter [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- you’re redefining a variable name that’s already in use, possibly declared in the function’s parameter list
‘TYPE’ does not name a type [ edit | edit source ]
- Message found in GCC version 4.5.1
- in GCC version 3.2.3 sometimes reported as: syntax error before ‘CHARACTER’ token
- in GCC version 4.0.1, sometimes reported as: ISO C++ forbids declaration
- e.g.: ISO C++ forbids declaration of ‘vector’ with no type
- you left out an object’s name qualifier or using directive
- make sure you didn’t mistype the scope operator «::», e.g.: «name:name» instead of «name::name»
- make sure you included the required libraries
- a header file is listed after a file that makes use of it in the include directives
expected ‘TOKEN’ before ‘TOKEN’ token [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- in GCC version 3.2.3 sometimes reported as: syntax error before ‘CHARACTER’ token
- check for a missing comma or parenthesis in a function’s parameters
- check for a missing semicolon
- e.g.: expected ‘,’ or ‘;’ before ‘TOKEN’
- possibly from a double namespace definition, or a fully-qualified (e.g., std::cout) name already under a ‘using’ directive
- possible missing ‘ >’ operator in a cin/cout statement
expected primary-expression before ‘TOKEN’ [ edit | edit source ]
expected unqualified-id before [ edit | edit source ]
- Message found in GCC version 4.5.1
- check your syntax for missing, misplaced, or erroneous characters
- expected unqualified-id before ‘(‘ token
- e.g.: parentheses in a class name
- expected unqualified-id before ‘return’
- e.g.: missing opening brace in a conditional statement
incompatible types in assignment of ‘TYPE’ to ‘TYPE’ [ edit | edit source ]
- Message found in GCC versions 4.5.1
- you’re trying to assign to or initialize a character array using a character pointer
- e.g.: incompatible types in assignment of ‘const char*’ to ‘char [10]’
- improperly accessing elements of a 2D array
invalid conversion from ‘TYPE’ to ‘TYPE’ [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- make sure parentheses were not left out of a function name
- make sure you are passing a function the correct arguments
invalid operands of types ‘TYPE’ and ‘TYPE’ to binary ‘FUNCTION’ [ edit | edit source ]
- Message found in GCC version 4.5.1
- You’re trying to concatenate to C string arguments with the addition operator
invalid use of template-name [ edit | edit source ]
is not a member of [ edit | edit source ]
- Message found in GCC versions 4.5.1
- check for a missing header include
example: ‘cout’ is not a member of ‘std’
‘TYPE’ is not a type [ edit | edit source ]
- Message found in GCC version 4.5.1
- in GCC version 3.2.3 reported as: type specifier omitted for parameter ‘PARAMETER’
- you mistyped a template parameter in a function declaration
- an included header file does not have the correct libraries included in the source file to implement it:
- e.g.: you’re using #include «bar.h» without including the «foo.h» that «bar.h» needs to work
- Check that there are no methods with the same name as ‘TYPE’.
‘CLASS_MEMBER’ is private within this context [ edit | edit source ]
- Message found in GCC versions 3.2.3, 4.5.1
- usually reported in the format:
- (LOCATION_OF_PRIVATE_DATA_MEMBER) error: ‘DATA_MEMBER’ is private
- (LOCATION_OF_CODE_ACCESSING_PRIVATE_DATA) error: within this context
- Message usually results from trying to access a private data member of a class or struct outside that class’s or struct’s definition
- Make sure a friend member function name is not misspelled
- make sure a read only function is using a ‘const’ argument type for the class
- make sure functions that alter data members are not const
- check for derived class constructors implicitly accessing private members of base classes
possible fix, assign the whole object rather than part of it:
Источник
Error: the conversion from ‘STD: : _List_const_iterator & lt; _Mylist> To non-scalar Type ‘STD ::_List_iterator< _Mylist> ‘the requested
Error C2440 resolved: “Initialize” : cannot be retrieved from “STD ::_List_const_iterator< _Mylist & gt;” Into “STD: : _List_iterator & lt; _Mylist & gt;”
Writing C++ code often USES const as a function argument, which is easy to do when using iterator if the variable is of type STL or contains type STL.
void list_print(const list<int> &list)
{
for (list<int>::iterator iter = list.begin();
iter != list.end();
++iter) {
...
}
}
The following error will be reported in this case
error C2440: “initialize”: cannot “std::_List_const_iterator<_Mylist>” to “std::_List_iterator<_Mylist>”
or
error: conversion from 'std::_List_const_iterator<_Mylist>' to non-scalar type 'std::_List_iterator<_Mylist>' requested
Here, because list itself is of type const, we need to use a const-type iterator, which is list::const_iterator
Code to
void list_print(const list<int> &list)
{
for (list<int>::const_iterator iter = list.begin();
iter != list.end();
++iter) {
...
}
}
done
Read More:
Ciao
Try this:
In file:
/home/…./components/arduino/libraries/WiFi/src/WiFiSTA.cpp:491
IPAddress WiFiSTAClass::dnsIP(uint8_t dns_no)
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPAddress();
}
// ip_addr_t dns_ip = dns_getserver(dns_no);
// return IPAddress(dns_ip.u_addr.ip4.addr);
const ip_addr_t * dns_ip = dns_getserver(dns_no);
return IPAddress(dns_ip->u_addr.ip4.addr);
}
In file:
/home/…./components/arduino/libraries/WiFi/src/ETH.cpp:196
IPAddress ETHClass::dnsIP(uint8_t dns_no)
{
//ip_addr_t dns_ip = dns_getserver(dns_no);
//return IPAddress(dns_ip.u_addr.ip4.addr);
const ip_addr_t * dns_ip = dns_getserver(dns_no);
return IPAddress(dns_ip->u_addr.ip4.addr);
}
This fix is from version 4.0 of the arduino-esp32 found here:
https://github.com/espressif/arduino-esp32/blob/idf-release/v4.0/libraries/WiFi/src/WiFiSTA.cpp
If you get the error «Please configure IDF framework to include mbedTLS -> Enable pre-shared-key ciphersuites and activate at least the path in menuconfig is:
component config > mbedTLS > TLS key exchange method > enable pre-shared keys & enable psk
Ivan
I’ve been browsing around google for a good amount of time and can’t grasp what is going on. I’m a noob in my 1st semester of c++ and this is an assignment for class.
Lines 33 and 34 in main when i call two functions. I get error:
conversion from `suns_record*’ to non-scalar type `suns_record’ requested
Can someone please explain what is causing the error in dumb dumb terms? It would be much appreciated.
|
|
I’m trying to make a simple program (I’m a noob) that reads in birthdays from a txt file, takes one new birthday in via user input, and then prints out birthdays that are upcoming within the week. It then prints the info back to the txt file. I keep getting the following error: «conversion from ‘Datee*’ to non-scalar type ‘Datee’ requested. I know that has something to do with pointers but I’m stuck. Please help and thanks in advance.
UPDATE: The first error was fixed with the help of Albert. There is now a new compile error: «request for member of non-aggregate type before ‘{‘ token. ‘findDays’ has not been declared». The two lines where it occurs are indicated below.
UPDATE: Second error fixed. The program is basically working now…just some tweaking and cleanup left. Thanks for the help!
Error 1: «conversion from ‘Datee*’ to non-scalar type ‘Datee’ requested.»
Error 2: «request for member of non-aggregate type before ‘{‘ token. ‘findDays’ has not been declared».
//main.cpp
#include <iostream> #include <fstream> #include <string.h> #include <cstring> #include <ctime> #include <sstream> #include <vector> #include "datee.h" int main(int argc, char *argv[]) { using namespace std; char dates [10]; _strdate(dates); char *tkn; string name[100], month[100], day[100]; int imonth, iday, cMonth, cDay, birthDays, currentDays; int Months[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; string smonth, sday, sname; tkn = strtok(dates, "/"); imonth = atoi(tkn); tkn = strtok(NULL, "/"); iday = atoi(tkn); Datee *currentDate = new Datee(iday, imonth); ifstream reader; reader.open("birthday.txt"); string tmp; int x = 0; while(reader.good()) { getline(reader, tmp); name[x] = tmp; getline(reader, tmp); month[x] = tmp; getline(reader, tmp); day[x] = tmp; x++; } cout << "enter a name: "; getline(cin, sname); cout << "enter a month(no zeros in front), or press <enter> to skip: "; getline(cin, smonth); stringstream(smonth) >> imonth; while(imonth < 1 || imonth > 12) { cout << "wrong! reenter: "; getline(cin, smonth); stringstream(smonth) >> imonth; } cout << "enter a day(no zeros in front), or press <enter> to skip: "; getline(cin, sday); stringstream(sday) >> iday; while(iday < 1 || iday > Months[imonth-1]) { cout << "wrong! reenter: "; getline(cin, sday); stringstream(sday) >> iday; } int t = x-1; name[t] = sname; month[t] = smonth; day[t] = sday; ofstream writer("birthday.txt"); for(int g = x; g >= 0; g--) { writer << name[g] << endl; writer << month[g] << endl; writer << day[g] << endl; } int daysUntil = 0; int h = x; do { smonth = month[h]; stringstream(smonth) >> imonth; sday = day[h]; stringstream(sday) >> iday; Datee *birthDate = new Datee(iday, imonth); birthDays = birthDate.findDays(); currentDays = currentDate.findDays(); daysUntil = birthDays - currentDays; if(daysUntil >= 0 && daysUntil <= 7) { cout << "Birthday is coming soon! " << daysUntil << " days to go until " << name[x] << "'s birthday!" << endl; } h--; }while(h >= 0); system("PAUSE"); return 0; } }</enter></enter></vector></sstream></ctime></cstring></string.h></fstream></iostream>
//datee.h
<pre lang="cs">#ifndef DATEE_H_ #define DATEE_H_ <pre lang="cs">class Datee{ public: Datee(int idays, int imths); int findDays(); private: int months[12]; int imths, idays, currentMonth, currentDay, totalDays; }; #endif
//date.cpp
#include "datee.h" Datee::Datee(int day, int mth) { imths = mth; idays = day; } int Datee::findDays() { months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; totalDays = 0; for(int i = 0; i < imths; i++) { totalDays += months[i]; } totalDays += idays; return totalDays; }
-
09-26-2011
#1
Registered User
error: conversion to non-scalar type requested
I cant seem to get past this error, I have dabbled with this for over an hour trying different methods to cast this .
typedef char NodeItemT;
typedef struct
{
NodeItemT info;
} NodeT;typedef struct
{
NodeT *list;
int capacity;
int size;
} VectorT;Code:
VectorT *new1(int cap) { int i; VectorT *init; init=(VectorT*)malloc (sizeof(VectorT)); init->capacity=cap; init->size=0; for(i=0;i<cap;i++) init->list[i].info=(NodeT)malloc(sizeof(NodeT)); //ERROR HERE return init; }
Last edited by camel-man; 09-26-2011 at 10:51 AM.
-
09-26-2011
#2
Registered User
Read this
Cprogramming.com FAQ > Casting mallocFYI: malloc always returns a pointer to the thing allocated!
Tim S.
-
09-26-2011
#3
C++ Witch
Do not cast the return value of malloc to begin with. Of course, not casting does not solve the problem, since the problem is that info is a char, and for some reason you are trying to assign a pointer to a char.
Originally Posted by Bjarne Stroustrup (2000-10-14)
I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.
Look up a C++ Reference and learn How To Ask Questions The Smart Way
-
09-26-2011
#4
Registered User
At first I had no malloc call and just had info = to » and it compiled and worked perfectly on Dev c++ but when I tried to run it on GCC it gave me a segmentation fault when I ran this function I am guessing it is because I dont have allocated space for the char, but Now I am stuck
-
09-26-2011
#5
C++ Witch
Originally Posted by camel-man
I am guessing it is because I dont have allocated space for the char
That is not true. Space is allocated for the char.
I suggest that you post the smallest and simplest (compilable) program that demonstrates the error.
Originally Posted by Bjarne Stroustrup (2000-10-14)
I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.
Look up a C++ Reference and learn How To Ask Questions The Smart Way
-
09-26-2011
#6
Registered User
Code:
int main() { VectorT *array; NodeItemT getting; char answer='y', chosenItem, IndexItem, chooseItem, theIt; int chosenIndex, index, chooseIndex, setInt, theIndex, theCap, theSize; int container, u, menu=0; while(answer=='y' || answer=='Y') { printf("-----Menu-----n"); printf("1-INITIALIZE a vectorn"); printf("2-ADD itemn"); printf("3-REMOVE itemn"); printf("4-INDEX checkn"); printf("5-SET itemn"); printf("6-GET itemn"); printf("7-CAPACITY checkn"); printf("8-SIZE checkn"); printf("9-CONTAINSn"); printf("10-CLEAR vectorn"); printf("11-DELETE vectorn"); printf("12-DISPLAY vectorn"); scanf("%i",&menu); switch(menu) { case 1: array=new1(15); break; /* IGNORE FROM HERE ON*/ case 2: printf("nSelect your Charactern"); scanf("%c",&chosenItem); scanf("%c",&chosenItem); add1(array,chosenItem); break; case 3: printf("nSelect Index at which you want to removen"); scanf("%i",&chosenIndex); remove1(array,chosenIndex); break; case 4: printf("nSelect Charactern"); scanf("%c",&IndexItem); scanf("%c",&IndexItem); index=indexOf(array,IndexItem); printf("Index is %in", index); break; case 5: printf("Put in the character you wish to setn"); scanf("%c",&chooseItem); scanf("%c",&chooseItem); printf("Pick at which indexn"); scanf("%i",&chooseIndex); setInt=set(array,chooseItem,chooseIndex); break; case 6: printf("Choose which index you would like to receiven"); scanf("%i",&theIndex); getting=get(array,theIndex); printf("You got %cn",getting); break; case 7: theCap=capacity(array); printf("Capacity is %in", theCap); break; case 8: theSize=size(array); printf("The Size is %in",theSize); break; case 9: printf("Enter in item to be testedn"); scanf("%c",&theIt); scanf("%c",&theIt); container=contains(array,theIt); if(container==1) printf("Yes the Vector Does Contain that Itemn"); else printf("No the vector does not contain that itemn"); break; case 10: clear(array); break; case 11: delete1(array); break; case 12: for(u=0;u<(array->capacity);u++) printf("%cn",array->list[u].info); break; } printf("Select 'Y' to continuen"); scanf("%c",&answer); scanf("%c",&answer); } return 0; } VectorT *new1(int cap) { int i; VectorT *init; init=(VectorT*)malloc (sizeof(VectorT)); init->capacity=cap; init->size=0; for(i=0;i<cap;i++) init->list[i].info=''; return init; }
Everything compiles fine until I enter in 1 to initialize the vector and it gives me a segmentation fault
-
09-26-2011
#7
Registered User
What is your definition of VectorT? What type is list and info? If you have an array of char* then you will need to allocate space for each one individually.
Originally Posted by anduril462
Now, please, for the love of all things good and holy, think about what you’re doing! Don’t just run around willy-nilly, coding like a drunk two-year-old….
Originally Posted by quzah
….. Just don’t be surprised when I say you aren’t using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.
-
09-26-2011
#8
C++ Witch
Originally Posted by camel-man
Everything compiles fine until I enter in 1 to initialize the vector and it gives me a segmentation fault
I tried to compile, and this is the list of errors reported by the MinGW port of gcc 3.4.5:
Code:
test.c: In function `main': test.c:3: error: `VectorT' undeclared (first use in this function) test.c:3: error: (Each undeclared identifier is reported only once test.c:3: error: for each function it appears in.) test.c:3: error: `array' undeclared (first use in this function) test.c:4: error: `NodeItemT' undeclared (first use in this function) test.c:4: error: syntax error before "getting" test.c:12: warning: implicit declaration of function `printf' test.c:28: warning: implicit declaration of function `scanf' test.c:33: warning: implicit declaration of function `new1' test.c:42: warning: implicit declaration of function `add1' test.c:48: warning: implicit declaration of function `remove1' test.c:56: warning: implicit declaration of function `indexOf' test.c:67: warning: implicit declaration of function `set' test.c:73: error: `getting' undeclared (first use in this function) test.c:73: warning: implicit declaration of function `get' test.c:79: warning: implicit declaration of function `capacity' test.c:84: warning: implicit declaration of function `size' test.c:93: warning: implicit declaration of function `contains' test.c:101: warning: implicit declaration of function `clear' test.c:105: warning: implicit declaration of function `delete1' test.c: At top level: test.c:134: error: syntax error before '*' token test.c:135: warning: return type defaults to `int' test.c:135: error: conflicting types for 'new1' test.c:33: error: previous implicit declaration of 'new1' was here test.c: In function `new1': test.c:137: error: `VectorT' undeclared (first use in this function) test.c:137: error: `init' undeclared (first use in this function) test.c:138: error: syntax error before ')' token
Originally Posted by Bjarne Stroustrup (2000-10-14)
I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.
Look up a C++ Reference and learn How To Ask Questions The Smart Way
-
09-26-2011
#9
Registered User
Here are the type defs
Code:
typedef char NodeItemT; typedef struct { NodeItemT info; } NodeT; typedef struct { NodeT *list; int capacity; int size; } VectorT;
Last edited by camel-man; 09-26-2011 at 11:22 AM.
-
09-26-2011
#10
C++ Witch
Originally Posted by camel-man
Here are the type defs
Better, but here is the new list of warnings and errors reported by the MinGW port of gcc 3.4.5:
Code:
test.c: In function `main': test.c:29: warning: implicit declaration of function `printf' test.c:45: warning: implicit declaration of function `scanf' test.c:50: warning: implicit declaration of function `new1' test.c:50: warning: assignment makes pointer from integer without a cast test.c:59: warning: implicit declaration of function `add1' test.c:65: warning: implicit declaration of function `remove1' test.c:73: warning: implicit declaration of function `indexOf' test.c:84: warning: implicit declaration of function `set' test.c:90: warning: implicit declaration of function `get' test.c:96: warning: implicit declaration of function `capacity' test.c:101: warning: implicit declaration of function `size' test.c:110: warning: implicit declaration of function `contains' test.c:118: warning: implicit declaration of function `clear' test.c:122: warning: implicit declaration of function `delete1' test.c: At top level: test.c:152: error: conflicting types for 'new1' test.c:50: error: previous implicit declaration of 'new1' was here test.c: In function `new1': test.c:155: warning: implicit declaration of function `malloc'
Remember to compile at a suitably high warning level and take note of the warnings too. They may indicate mistakes that you have made. I compiled with -Wall and -pedantic.
Originally Posted by Bjarne Stroustrup (2000-10-14)
I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.
Look up a C++ Reference and learn How To Ask Questions The Smart Way
-
09-26-2011
#11
Registered User
Ok well here is the whole post sorry I kept leaving stuff out
Code:
#include <stdio.h> #include <stdlib.h> typedef char NodeItemT; typedef struct { NodeItemT info; } NodeT; typedef struct { NodeT *list; int capacity; int size; } VectorT; NodeT *newNode(NodeItemT item); VectorT *new1(int cap); void add1(VectorT *vector, NodeItemT item); void remove1(VectorT *vector, int index); int capacity(const VectorT *vector); int size(const VectorT *vector); void clear(VectorT *vector); NodeItemT get(const VectorT *vector, int index); int set(VectorT *vector, NodeItemT item, int index); int indexOf(const VectorT *vector, NodeItemT item); void delete1(VectorT *vector); int contains(const VectorT *vector, NodeItemT item); int main() { VectorT *array; NodeItemT getting; char answer='y', chosenItem, IndexItem, chooseItem, theIt; int chosenIndex, index, chooseIndex, setInt, theIndex, theCap, theSize; int container, u, menu=0; while(answer=='y' || answer=='Y') { printf("-----Menu-----n"); printf("1-INITIALIZE a vectorn"); printf("2-ADD itemn"); printf("3-REMOVE itemn"); printf("4-INDEX checkn"); printf("5-SET itemn"); printf("6-GET itemn"); printf("7-CAPACITY checkn"); printf("8-SIZE checkn"); printf("9-CONTAINSn"); printf("10-CLEAR vectorn"); printf("11-DELETE vectorn"); printf("12-DISPLAY vectorn"); scanf("%i",&menu); switch(menu) { case 1: array=new1(15); break; case 2: printf("nSelect your Charactern"); scanf("%c",&chosenItem); scanf("%c",&chosenItem); add1(array,chosenItem); break; case 3: printf("nSelect Index at which you want to removen"); scanf("%i",&chosenIndex); remove1(array,chosenIndex); break; case 4: printf("nSelect Charactern"); scanf("%c",&IndexItem); scanf("%c",&IndexItem); index=indexOf(array,IndexItem); printf("Index is %in", index); break; case 5: printf("Put in the character you wish to setn"); scanf("%c",&chooseItem); scanf("%c",&chooseItem); printf("Pick at which indexn"); scanf("%i",&chooseIndex); setInt=set(array,chooseItem,chooseIndex); break; case 6: printf("Choose which index you would like to receiven"); scanf("%i",&theIndex); getting=get(array,theIndex); printf("You got %cn",getting); break; case 7: theCap=capacity(array); printf("Capacity is %in", theCap); break; case 8: theSize=size(array); printf("The Size is %in",theSize); break; case 9: printf("Enter in item to be testedn"); scanf("%c",&theIt); scanf("%c",&theIt); container=contains(array,theIt); if(container==1) printf("Yes the Vector Does Contain that Itemn"); else printf("No the vector does not contain that itemn"); break; case 10: clear(array); break; case 11: delete1(array); break; case 12: for(u=0;u<(array->capacity);u++) printf("%cn",array->list[u].info); break; } printf("Select 'Y' to continuen"); scanf("%c",&answer); scanf("%c",&answer); } return 0; } NodeT *newNode(NodeItemT item) { NodeT *node; node = (NodeT*) malloc (sizeof(NodeT)); node->info=item; return node; } VectorT *new1(int cap) { int i; VectorT *init; init=(VectorT*)malloc (sizeof(VectorT)); init->capacity=cap; init->size=0; for(i=0;i<cap;i++) init->list[i].info=''; return init; } void add1(VectorT *vector, NodeItemT item) { NodeT *tempList; int i; if((vector->size)>=(vector->capacity)) { tempList=(NodeT*)malloc(((vector->capacity)*2)*sizeof(NodeT*)); for(i=0;i<vector->capacity;i++) tempList[i]=vector->list[i]; for(i=vector->capacity;i<((vector->capacity)*2);i++); tempList[i].info=''; vector->list=tempList; vector->capacity=((vector->capacity)*2); } vector->list[vector->size].info=item; vector->size=(vector->size)+1; } void remove1(VectorT *vector, int index) { int i; vector->list[index].info=''; if(index>(vector->size)||index<0) printf("ERROR INVALID INPUTn"); else if((vector->list[index].info)=='') { for(i=index;i<(vector->size);i++) { vector->list[i]=vector->list[i+1]; } vector->list[vector->size].info=''; vector->size=(vector->size)-1; } } int capacity(const VectorT *vector) { return vector->capacity; } int size(const VectorT *vector) { return vector->size; } void clear(VectorT *vector) { int i; for(i=vector->size;i>=0;i--) vector->list[i].info=''; vector->size=0; } NodeItemT get(const VectorT *vector, int index) { if(index>(vector->capacity)) printf("ERROR OUT OF RANGE OF VECTOR"); else return vector->list[index].info; } int set(VectorT *vector, NodeItemT item, int index) { if(index<(vector->capacity)) { vector->list[index].info=item; return index; } else return -1; } int indexOf(const VectorT *vector, NodeItemT item) { int i; for(i=0;i<(vector->size);i++) if(vector->list[i].info==item) return i; } void delete1(VectorT *vector) { free(vector); } int contains(const VectorT *vector, NodeItemT item) { int i; for(i=0;i<=vector->size;i++) { if(vector->list[i].info==item) return 1; } return 0; }
-
09-26-2011
#12
C++ Witch
Ah, two more:
Code:
test.c: In function `get': test.c:244: warning: control reaches end of non-void function test.c: In function `indexOf': test.c:265: warning: control reaches end of non-void function
The first one is not really a problem because you are printing an error message in that case, though perhaps you could consider #include <assert.h> and then write:
Code:
NodeItemT get(const VectorT *vector, int index) { assert(index <= vector->capacity || !"ERROR OUT OF RANGE OF VECTOR"); return vector->list[index].info; }
Anyway, now I can tell you this: in new1, observe that init->list is a pointer. However, you did not allocate any space for the elements, yet you access init->list[i].
Originally Posted by Bjarne Stroustrup (2000-10-14)
I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.
Look up a C++ Reference and learn How To Ask Questions The Smart Way
-
09-26-2011
#13
Registered User
yes you are right I just did and it is working so far so good thanks for your time I do appreciate it