user3179839
user3179839

Reputation: 1

Segmentation fault using strcat using a single character

Here is my code:

int min = 0, i, z;
char star[18][100] = {0};
int temp = 0;
char TheStar[2];
TheStar[0] = '*';
TheStar[1] = '\0';


for(i = 0; i < 17; i++){
    if(min == 0 && PerHundredThousand > 0)
     min = PerHundredThousand[i];
    if(PerHundredThousand[i] < min)
     min = PerHundredThousand[i];}


for(z = 0; z < 17; z--){
     if(PerHundredThousand[z] > 0)
      temp = PerHundredThousand[z] / min;
     while(temp > 0){
         strcat(star[z], TheStar);
         temp = temp - 1;}

}

As you can see i'm trying to use strcat to add a '*' as long as temp is higher than 0 but I get a segmentation fault on:

strcat(star[z], TheStar);

Any help is appreciated. Thanks in advance.

Upvotes: 0

Views: 67

Answers (2)

Mubin Icyer
Mubin Icyer

Reputation: 705

In the first loop there is a mistake

if(min == 0 && PerHundredThousand > 0) 

should be

if(min == 0 && PerHundredThousand[i] > 0)

Upvotes: 1

Mark Wilkins
Mark Wilkins

Reputation: 41222

The second loop appears wrong:

for(z = 0; z < 17; z--){

Should probably be:

for(z = 0; z < 17; z++){

Otherwise it would loop a lot more times than intended (as well as write to invalid array positions).

Upvotes: 3

Related Questions