Good day to all who did not greet. Continuing with a question on a previous topic - >> Invalid conversion from `char * 'to` char'

I will build on the previous topic.


The size of the text and result lines is arbitrary. With pointers I did not work and we will continue to learn. I applied static and toupper to the code. Thanks avp .

As for the rest of the questions about avp quotes:

We think about it, and what else to do and return the length of result[] .

(By the way, here is the right code that you have now, so it is generally wrong. The memory 'text [12]' and 'result [12]' is not initialized, there may be any characters, just print the codes:

 int i; for (i = 0; i < 12; i++) printf("0x%02x ", (unsigned char)text[i]); puts(""); 

)

And let's say at the beginning there is all a and you read the string bc . You bc\000aaaaaaaaa " bc\000aaaaaaaaa " and what will happen after the call to search() ?


I did not understand about the return length result[] .

I did not understand about the initialization of 'text [12]' and 'result [12]'

I did not understand what the code in the quote is and what this cycle does, what incomprehensible numbers "0x%02x" and the phrase at the beginning of the argument (unsigned char)text[i] .

I did not understand about "" bc \ 000aaaaaaaaa "'.


The code of my program is below and there is this function for finding vowels. I apologize if it reaches me tightly, but with grief in half, I try to understand what works and how. Thanks in advance for the answers!

And the question about which function to enter a string from? fgets, gets or scanf?

 #include <iostream> #include <conio.h> void search(char text[], char result[]); void sorting(char result[]); main(){ char text[12]; char result[12]; int c; printf("This programm search vocal words and sorting their.\n\nInstruction:\n\n1. Enter simple text\n2. See result\n\nEnter simple text: "); fgets(text, 12, stdin); c = strlen(text); //считаем и сажаем в последнюю ячейку нулевой символ text[c + 1] = 0; search(text, result); //эта функция ищет гласные в text и сажает их в result getch(); } void search(char text[], char result[]){ static char vocal[6] = {'A', 'E', 'O', 'Y', 'U', 'I'}; //регистр гласных int i, j, c, v = 0; c = strlen(text); for(j = 0; j < c; j++){ //сравниваем, начиная с первой буквой регистра for(i = 0; i < c; i++){ //сравниваем, начиная с первой буквы строки if(toupper(text[j]) == vocal[i]){ result[v] = text[j]; v++; } } } printf("\nVocal words: %s", result); } 

    1 answer 1

    @DrummerIF , it's great that you try.

    About the current code.

    Writing text[c + 1] = 0 not only unnecessary, but also dangerous. Needless to say, since (read man fgets ) fgets always writes zero after the data read into the buffer. If we enter (from the keyboard) more characters than can fit in the buffer, then (for your case fgets(text, 12, stdin) ) 11 bytes will be placed in text[] , and in text[11] fgets () will write itself 0
    It is dangerous because in the considered case, strlen(text) returns 11, and you write down 0 in text [11 + 1], i.e. for the last byte allocated for the array.

    So, just throwing this fragment as unnecessary.

    Now look at search() .

    Yes, the idea to view not all, but only the entered characters in the text [] is absolutely correct
    (using the same variable c in the cycle by vocal [] is an obvious mistake, probably a mistake).

    Looking at the code a little more closely and thinking about how the strlen function can be implemented and knowing that the “strings” in C are arrays of bytes, terminating in zero, we can conclude that the call to strlen in this context is superfluous. We’ll still go through the text [] characters, so nothing can stop us from finding the end of the line ourselves as we go.
    For example, a loop on text [] characters might look like this:

      for (j = 0; text[j]; j++) 

    Obviously, a nested loop on vowels can (and probably a uniform code is really good) to organize the same way by adding a zero byte to its end.
    (by the way, then it would be possible to describe the vowels quite simply:

     static char vocal[] = "AEOYUI"; 

    )

    But, for a variety of techniques, we will go the other way and use the variable c (everyone will start swearing here that this is a bad name, the names of the variables should ... (this will tell you all who feel)) to calculate the size of the vocal [6] So:

     с = sizeof(vocal) / sizeof(vocal[0]); 

    (It would seem - dope. The very line above wrote that the size of vocal 6! But, in some situations it is better to calculate.)

    This is a standard technique for obtaining the number of elements in an array. Pay attention to the true size of the array at this point should be known to the compiler (we have search () inside for this is true for vocal [], but not for text [] and result [] , which are actually created (i.e., memory is allocated for them) in the calling function).

    Go ahead and notice that after we find that text [i] is a vowel, we don’t need to sort through the remaining vowels. As a result, the main function code becomes:

      с = sizeof(vocal) / sizeof(vocal[0]); for (i = 0; text[i]; i++) for (j = 0; j < c; j++) if (toupper(text[i]) == vocal[j]) { result[v++] = text[i]; // обычная сишная "красивость", совместим индексацию с изменением индекса в одном выражении break; // в самом деле, раз нашли, так пойдем сразу дальше по text[] } result[v] = 0; // обязательно завершим список обнаруженных гласных 0 

    Should we then go back to main, where memory was allocated to result [] and increase it by 1?
    (the answer is no, there is just enough memory, since the same 0 is necessarily entered into text [] by the fgets function)

    Now about the questions.

    • Why return the length of the result? For beauty, completeness, expansion of functionality, possible simplification of use of search (). In fact, you get an answer to questions for free, but are there any vowels? and how many vowels are there?

    Then the prototype will be like this:

     int search (char text[], char result[]); 

    Well, the implementation should change accordingly:

     int search (char text[], char result[]) { ... return v; } 

    About a possible remark about the choice of the type of the function int - and not size_t I would say - let's leave room for maneuver - for example, the ability to return errors (or make some other functional extension).

    • I did not understand about the initialization of 'text [12]' and 'result [12]'
      I did not understand what the code in the quote is and what this cycle does, what incomprehensible numbers "0x% 02x" and the phrase at the beginning of the argument (unsigned char) text [i].
      I did not understand about "" bc \ 000aaaaaaaaa "'.

    Speech about initialization, as far as I remember, was in the context of the code in search ()

     for (i = 0; i < 12; i++) ... if (... text[i] ... 

    those. about access to potentially undefined bytes. I think in the light of the foregoing, this has become irrelevant.

    The code in the quote displays the hexadecimal values ​​of the first 12 bytes of the text [] array (to illustrate that anything could be there). "0x% 02x" - this format says:

     выведи пару символов `0` и `x` выведи шестнадцатеричное значение (очередного) аргумента printf, который д.б. типа int в случае одной цифры выведи лидирующий 0. 

    (And you read man 3 printf , and practice).

    '"bc \ 000aaaaaaaaa"' is very simple (in the C book, you have to have it somewhere) when writing character strings (they can also initialize arrays (it seems I have already shown this above)) any character can be written as backslash and further 3 digits of its octal code .

    • from which function to enter a string? fgets, gets or scanf?

    Entering a string is better with the fgets () function, since it checks for a buffer overflow.
    When using GNU (gcc and the corresponding libc library), the getline () function is also convenient (read man getline , at the same time learn the pointers). As I understand it, you are using Windows, so an independent implementation of getline (hopefully in the near future) m. great exercise (and at the same time a test of learning C)).