access violation error
Koroskin Denis
2korden at gmail.com
Wed Aug 13 14:39:13 PDT 2008
On Thu, 14 Aug 2008 01:23:05 +0400, Wyverex <wyverex.cypher at gmail.com>
wrote:
> Michael P. wrote:
>> /* junior304.d
>> 2008 junior problem 3
>> Smile with similies
>> Ask for 2 numbers; the number of adjectives and nouns
>> After you get the numbers and nouns and adjectives, out all possible
>> similies
>> August 12th, 2008 */
>> //Imports
>> import std.stdio;
>> /*****
>> *Main*
>> *****/
>> void main()
>> {
>> int numberOfAdjectives;
>> scanf( "%d", &numberOfAdjectives );
>> int numberOfNouns;
>> scanf( "%d", &numberOfNouns );
>>
>> char[][] adjectives; //array of strings to hold the adjectives
>> adjectives.length = 6; //max number that user enters is 5, 6 to be
>> safe char[][] nouns; //same as above, but for nouns
>> nouns.length = 6; //same as adjectives reason
>>
>> //get adjectives first
>> for ( int i = 0; i < numberOfAdjectives; i++ ) //get the specified #
>> of adjectives
>> {
>> scanf( "%s", &adjectives[ i ] );
>> }
>>
>> //now get the # of nouns specified
>> for ( int i = 0; i < numberOfNouns; i++ )
>> {
>> scanf( "%s", &nouns[ i ] );
>> }
>>
>> //print out all possible similies
>> for ( int i = 0; i < numberOfAdjectives; i++ )
>> {
>> for ( int j = 0; j < numberOfNouns; j++ )
>> {
>> //for every adjective, place a noun after and turn it into a similie
>> writefln( "%s as %s", adjectives[ i ], nouns[ j ] );
>> }
>> }
>> }
>> I get an accessviolation when I enter the last 2 for loops; any
>> reason why?
>> Input is:
>> 3
>> 2
>> Easy
>> Soft
>> Smart
>> pie
>> rock
>> error!
>
Your code is seriously broken!
The following line is wrong, for example:
> scanf( "%s", &nouns[ i ] );
What are you doing here? Are you out of your mind? You are passing a
pointer to a char[]* to a function that accept a char*. Your array will be
overwritten with whatever you will type. It is wrong, wrong, wrong!
I think that you don't understand something. First of all, what is a
char[]? It is a struct that consists of a array size and a pointer:
struct CharArray {
size_t size;
char* ptr;
}
typeof(nounts[i]) is a char[], typeof(&nouns[i]) is char[]*. You pass this
pointer to a function that accepts a pointer to a preallocated buffer for
a string to be written to.
A quick fix would be to:
1) allocate a buffer:
nouns[i] = new char[64];
2) pass a pointer to the preallocated buffer:
scanf("%s", nouns[i].ptr);
A good fix would be to use readf instead. I didn't use it, but this should
be sufficient:
readf("%s", &nouns[i]);
> quick fix is to use printf
> printf( "%s as %s", &adjectives[ i ], &nouns[ j ] );
>
> i think (not sure don't really use phobos that much) scanf doesn't
> return strings in a format writef likes...
>
> I though theres a readf but cant find documentation on it...
Test before posting, please!
More information about the Digitalmars-d-learn
mailing list