Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm working on an assignment where the program needs to print out a rectangular spiral matrix made out of characters with a given string.
string is :
   const char C[71] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 .,-!?()";

given 2 dimensional matrix:
char M[70][70];

When i compile the program on Xcode it outputs random characters, but when i compile it online on cpp shell, the matrix is printed out. Does anyone know the reason to this and how to solve it?

example of the random characters:
\340\215\270\216\354\217\340\220\370\221\340\222Ë“\212\225\250\226
Ö˜\245\232\300\233?\235&\236P\237\270\240\242@\243
\256\273\257\243\260\234\261\247\262\200\263\344\264X\266Z\267
x\270P\271Z\272\220\273\375\274\250\276\300


here is my code:
 void showSetting() {
        cout<<"W="<<W<<", H="<<H<<endl;
        int i,startRow = 0, endRow, startCol = 0;
        int counter=0;
            
            endRow = H-1;
 
           while(startRow <= endRow && startCol <= W) {
        for (i = startCol; i < W; i++) {
            M[startCol][i] = C[counter];
            counter++;
        }
        startRow++;

        for (i = startRow; i < endRow; i++) {
            M[i][W] = C[counter];
            counter++;
        }
        W--;

        if (startRow <= endRow) {
            for (i = W; i >= startCol; i--) {
                M[endRow][i] =C[counter];
                counter++;
            }
            endRow--;
        }

        if (startCol <= W) {
            for (i = endRow; i >= startRow; i--) {
                M[i][startCol] = C[counter];
                counter++;
            }
            startCol++;
        }
             
    }
        
    
    for(i = 0; i <70; i++) {
        for (int j = 0; j <70; j++) {
            cout<<M[i][j];
        }
cout<<endl;
    }


What I have tried:

Since I'm new to programming I have don't what is the cause of this and how to solve it.
Posted
Updated 22-Nov-22 5:56am

IMHO it should not work correctly nowhere...

C++
C[counter]
This part is easily overflow even for small rectangles... It has only 72 members, but even for a 10-by-10 rectangle you need a 100 signs...
You should MOD counter by the length of C...
 
Share this answer
 
You are mismatching the types of variables. At first give clear names to your variables like C and M.
C++
C[counter];
give you a character at position counter. If it is greater than your fix array you get some garbage from other memory.

Try with starting some Learn C++ tutorial or some video tutorial.

some tips: use functions and classes with understandable names and install some IDE like Visual Studio.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900