-1

I'm writing a simple program in c, that prints all elements of an array. The array is

char op[2][50] = {"option1", "option2"};

the program is

int main(int argc, char * argv[])
{
    char spaces[6] = "      ";
    int choice;
    char op[2][50] = {"option1", "option2"};

    printf("\n\n\t=========== OPTIONS ===========\n\n\t");
    for (int i;i<sizeof(op)/sizeof(op[0]);i++) {printf("%s[%d]: %s\n\t",spaces,i+1,op[i]);}
    printf("\n\t\t%s[?]: ",spaces);
    scanf("%d",&choice);
    
    if (choice==1) {firstFunction();} //i've declared this function, but here isn't important

    return 0;
}

So, the problem is that the options arent printed. output:

=========== VIDEO TOOLS ===========


               [?]:

the problem is essentially that if statement, because i've tried to add other printf up and down it and them works. Also, that if statement worked before some changes to the program, so the problem can be other lines of code(?)

i'm a beginner with c, so please not expose complex solutions. thanks

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
cow boy
  • 1
  • 1
  • 2
    What is the value of `i`? – Fe2O3 Sep 26 '22 at 09:13
  • The size of `spaces` is to small to hold the string you want it to hold. Remember that strings in C are really called ***null-terminated** strings*. That means a string of six characters really need space for seven, to be able to hold the terminator. Drop the size-specification for `spaces` to solve that issue: `char spaces[] = " ";` – Some programmer dude Sep 26 '22 at 09:15
  • 1
    Make it a habit to _end_ your printf lines with `\n` rather than to begin with them. Because `\n` does not only change the line, it may also flush the stdout on some systems. Failing to flush stdout might cause the output to appear in a strange order or go missing. – Lundin Sep 26 '22 at 09:15
  • `i'm a beginner with c`... Then you still have time to NOT get used to using (and wasting hours chasing problems arising from using) `scanf( )` Run away! Figure out how to use `fgets()` and deal with the "line at a time" input it can deliver. Don't be lazy... Too many SO questions because of abuse and misuse of `scanf()`... Not recommended... – Fe2O3 Sep 26 '22 at 09:36
  • @Fe2O3 i've tried fgets! but i have a problem.. if i use two consecutive fgets, the first fgets doesn't work.. do you know how can i solve? – cow boy Sep 26 '22 at 09:39
  • `the first fgets doesn't work..` Hardly the case. `fgets( )` is used in millions of programs around the world and it **works**... No, I cannot solve your problem because I do not read minds... If you make a serious effort and experience difficulties, post the (small) code example as a new question to SO and get **expert** advice on what's wrong and how to fix it... Stay away from `scanf( )`... It _can_ work if the input conforms to the programmer's expectations. Otherwise, it doesn't... – Fe2O3 Sep 26 '22 at 09:45
  • Rather, don't waste a lot of time learning console I/O. People stopped using such almost 30 years ago, with the advent of GUIs. Just regard console stuff as quick & dirty debugging aid, not something to use in production code. – Lundin Sep 26 '22 at 10:23

3 Answers3

0

for (int i;i<sizeof(op)/sizeof(op[0]);i++)

You do not initialize the i variable and it is an Undefined Behaviour (UB)

It should be:

for (int i = 0;i<sizeof(op)/sizeof(op[0]);i++)

or better (using the correct type for sizes and positive indexes)

for (size_t i = 0;i<sizeof(op)/sizeof(op[0]);i++)

To print size_t use %zu format

Also, remember that C string is terminated by the null terminating character. So you need to add one more character than seen in the string literal. ("123" requires 4 characters) spaces array is too short to accommodate " ". char spaces[] = " ";

0___________
  • 60,014
  • 4
  • 34
  • 74
0

Lots of bugs. Summary of things mentioned in comments:

  • i is used while uninitialized, set it to zero.

  • char spaces[6] = " "; is too small, see How should character arrays be used as strings?.

  • Make it a habit to end your printf lines with \n rather than to begin with them. Because \n does not only change the line, it may also flush the stdout on some systems. Failing to flush stdout might cause the output to appear in a strange order or go missing.

Also in case these are read-only strings, then consider using a 1D array of pointers instead, since that's more flexible and memory efficient:

const char* op[2] = {"option1", "option2"};
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Good to point out that "specifying 6" was a bad move. Better to let the compiler measure things. But, then, to set the size of the array of pointers to `2` and dictate to the compiler that dimension??? Odd... – Fe2O3 Sep 26 '22 at 09:53
0

This array declaration where the number of elements is specified explicitly:

char spaces[6] = "      ";

is error prone. The array does not contain a string because the terminating zero character '\0' of the string literal used as an initializer is not stored in the array spaces. The size of the string literal is equal to 7 not to 6.

So it is safer to write:

char spaces[] = "      ";

Or as you are not going to change the array then it will be better to write:

const char *spaces = "      ";

In this declaration of the two-dimensional array:

char op[2][50] = {"option1", "option2"};

you explicitly specified that the array contains two elements. So using the expression i<sizeof(op)/sizeof(op[0]) does not make a great sense.

Either introduce a named constant before the declaration of the array, like for example:

enum { N = 2 };
char op[N][50] = {"option1", "option2"};

and then use the expression:

i < N

in the for loop. Or declare the array like:

char op[][50] = {"option1", "option2"};

and after the declaration introduce a named constant like:

const size_t N = sizeof( op )/sizeof( op[0] );

and use the constant in the for loop where by the way you forgot to initialize the variable i

for ( size_t i = 0; i < N; i++ ) 
{
    printf("%s[%zu]: %s\n\t",spaces,i+1,op[i]);
}

As the variable i now has the type size_t then you have to use the conversion specifier %zu instead of %d in the call of printf.

It will be safer to rewrite this code snippet

scanf("%d",&choice);

if (choice==1) {firstFunction();} // I've declared this function, but here isn't important

The following way:

if ( scanf("%d",&choice) == 1 && choice==1 ) 
{
    firstFunction();
} // I've declared this function, but here isn't important
halfer
  • 19,824
  • 17
  • 99
  • 186
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335