Frage

I have this function that will make an array of chars (ie a string) into a right triangle. It works but then it keeps going even after the array has stopped. So the output always has many extra lines of blank space.

and if the word is long enough random symbols will appear at the end of that blank space. This is probably because the blank space exited the arrays size of 100. I dont know whats causeing this. I tried to set conditions to the counter and the printf that makes a new line but that just breaks the code entirely. I thought it was definitely the printf for new lines doing it but it doesnt seem like it now after trying that. Does anyone see whats wrong?

Below is the remote function from my code.

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>


#define clear system("cls") 
#define pause system("pause") 


void triangulate(char stringArray[]){
    int i,j,len = 0;
    int counter=0;
    len=strlen(stringArray);//a function library function that returns the length

    printf("\n");
    for(i=1;i<=len;++i){
        for(j=1;j<=i;++j){
            printf("%c",stringArray[counter]);
            counter++;
        }
        printf("\n");

    }
    printf("len:%i counter:%i",len, counter);
    pause;
}//end triangulate()
War es hilfreich?

Lösung

This is wrong:

for(i=1;i<=len;++i) {
    for(j=1;j<=i;++j) {
        printf("%c",stringArray[counter]);
        counter++;
    }
    printf("\n");
}

You can't increment counter so many times. Because of the nested loops, counter will access out of bounds positions - you are incrementing it towards a final value that is O(n^2) with relation to the string's length.

Andere Tipps

Let's consider the following simple case:

stringArray = "abc";

and see what happens in the two loops:

i = 1; j = 1; counter = 0;
i = 2; j = 1; counter = 1;
i = 2; j = 2; counter = 2;
i = 3; j = 1; counter = 3; // Undefined behaviour since stringArray[counter]
                           // is out of bounds

and so on (however, once you hit undefined behaviour, all bets are off and your program is free to do whatever it wants).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top