Slavko Kovačević Slavko Kovačević - 11 days ago 6
C Question

Why break gets me out of 2 loops at once and how to fix it

Ok, so the idea of the task I have (I am the student) is to allow user to insert a string of words in this form: num1_num2_num3..._numN. The code should create an array X, give it memory dynamically and then I should fill X with numbers from string user inserted. Simple as that. Well, in the function

stringuniz()
I thought I had it all figured out but it simply wont work. It gets the first number well but it then stops and I think its because of the break. Break behaves (if I am right) like it breaks the entire code and not just the loop. Do you guys have an idea why is this happening?

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

void stringuniz(char *);
int *x;

int main(){

char s[50];
int i;

puts("Unesite string brojeva u formatu br1_br2_...brN: ");
gets(s);

stringuniz(s);

for(i=0;i<(sizeof(x)/sizeof(int));i++)
printf("%d",x[i]);
}

void stringuniz(char *s){

int duz,c=0,i,j,k=0,m=0;
char b[10];

duz=strlen(s);

for(i=0;i<duz;i++)
if(s[i]=='_')
c++;

x=(int*)malloc((c+1)*sizeof(int));
if(x==NULL) exit(1);

for(i=0;i<c+1;i++){
for(j=m;j<duz;j++){
if(s[j]!='_'){
b[k++]=s[j];
m++;
}
else{
b[k]='\0';
x[i]=atoi(b);
k=0;
m++;
break;
}

}
}
}

Answer

This

(sizeof(x)/sizeof(int) 

won't give you the size of the array. sizeof(x) is the bytesize of int* (likely 4 or 8). You'll need to remember the size as implied by the number of _ in the string.

Also you have some off-by-one errors in there and for future reference, you might want to choose more descriptive variable names for code you decide to post publicly.

The code worked for me once I changed it to:

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

void stringuniz(char *);
int *x;
int x_size = 0;

int main(){
    char s[50];
    int i;
    puts("Unesite string brojeva u formatu br1_br2_...brN: ");
    fgets(s,50,stdin);
    stringuniz(s);
    for(i=0;i<x_size;i++)
        printf("%d\n",x[i]);
}
void stringuniz(char *s){
    int duz,c=0,i,j,k=0,m=0;
    char b[10];
    duz=strlen(s);
    for(i=0;i<duz;i++)
        if(s[i]=='_')
            c++;
    x=malloc((c+1)*sizeof(int));
    x_size = c+1;
    if(x==NULL) exit(1);
    for(i=0;i<=c+1;i++){
        for(j=m;j<=duz;j++){
            if(s[j]!='_' && s[j]!='\0'){
                b[k++]=s[j];
                m++;
            }
            else {
                b[k]='\0';
                x[i]=atoi(b);
                k=0;
                m++;
                break;
            }

        }
    }
}