how to change to c code while using for loop and array

Let’s start with the C++ code because it contains a bug.

    string element[2];            // Array with 2 string

    cout<<"Enter amount data: ";
    cin>>num;                     // Read a number


    cout<<"Elements are: ";
    for(b=0;b<num;b++){           // Use the number as limit
        cout<<" "<<element[b];    // Print all string from 0 to number-1

So if I give the program the input 42, the program will access element[0], element[1], element[2], element[3], …., element[41] but the array only has 2 elements so the program is accessing outside the array, i.e. the program has undefined behavior.

Converting an ill-formed C++ program to C seems pretty pointless but — of course — it can be converted into a likewise ill-formed C program.

So for the C program:

Rule #1

Set your compiler to highest warning level and fix all warnings

In C programming the warnings you get from the compiler is very often an indication of a bug. Therefore you must take warnings seriously and get them fixed. Don’t even run your program if the compiler generates just a single warning. Make sure you have a clean compile (i.e. warning free compile) first.

Now compiling your program with “gcc -Wall” gives me:

main.cpp: In function 'main':
main.cpp:8:11: error: array size missing in 'str'
    8 |      char str[];
      |           ^~~
main.cpp:12:14: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=]
   12 |      scanf("%d",num);
      |             ~^  ~~~
      |              |  |
      |              |  int
      |              int *
main.cpp:19:14: error: invalid type argument of unary '*' (have 'int')
   19 |              *str[0]="A";
      |              ^~~~~~~
main.cpp:21:14: error: invalid type argument of unary '*' (have 'int')
   21 |              *str[1]="B";
      |              ^~~~~~~
main.cpp:26:15: error: invalid type argument of unary '*' (have 'int')
   26 |          puts(*str[b])
      |               ^~~~~~~
main.cpp:26:23: error: expected ';' before '}' token
   26 |          puts(*str[b])
      |                       ^
      |                       ;
   27 |      }
      |      ~                 
main.cpp:7:14: warning: unused variable 'data' [-Wunused-variable]
    7 |      int a,b,data[num];
      |              ^~~~

So you have 2 warnings (one of them is an actual error) but even worse, you also have 5 errors. All this tells you what to fix.

Your main issue is strings! The way you try to convert the C++ type string to C type string is wrong. So here is a little explanation of strings in C.

There is no string type in C !


char str[];   // is NOT in any way compatible with C++ string element[2];

(It’s actually an error in C.)

C strings are a special usage of a char array. The special usage is that one element in the char array must have the value '\0' (aka NUL). This element then signals END-OF-STRING.

So consider this:

char strA[2] = "A"; // strA[0] is 'A' and strA[1] is '\0'

In this way you have made a C string equal to “A”. Notice: The string length is 1 but the array still needs two chars. That’s because an extra char is needed for the '\0' to signal END-OF-STRING.

So if you want an array with two strings to hold either “A” or “B”, you need to do:

 char str[2][2];  // instead of just char str[];

Further, you can’t use = to assign values to strings in C. You need strcpy (“string copy”). Like:

strcpy(str[0], "A");  // instead of str[0] = "A"

Finally, to print the string with a newline after it, just use:

puts(str[0]);  // or puts(str[1]);

Browse More Popular Posts

Leave a Comment