LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   gcc is noughty on my c code. (https://www.linuxquestions.org/questions/programming-9/gcc-is-noughty-on-my-c-code-4175438039/)

suttiwit 11-20-2012 07:09 PM

gcc is noughty on my c code.
 
Hello all..
I am making a code that prints random characters from the template.
Thing is.. I make a printf() and specify template[ch]. when 'template' is a char and 'ch' is an int to specify where in the char it will print.
But gcc does not look at template. it looks at 'ch' and thought it was int.

I don't know who's fault this is (gcc or me). Here is the code:
Code:

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

int main(void)
{
        char template[999] = "qwertyuiopasdfghjklzxcvbnm1234567890äåéëþüúíóö«»áßðø¶æ©®bñµç.¿¹²³¤^¥×¡,~_£¼½¾,~*÷ÄÅÉËÞÜÚÍÓÖÁ§ÐÏØÆ¢°®ÑµÇ";
        int ch;
        for (;;)
        {
                ch = rand() % strlen(template);
                printf("%s", template[ch]);
                fflush(stdout);
        }
        return 0;
}

I need it soon! THanks in advance.

Sergei Steshenko 11-20-2012 07:42 PM

Quote:

Originally Posted by suttiwit (Post 4833669)
Hello all..
I am making a code that prints random characters from the template.
Thing is.. I make a printf() and specify template[ch]. when 'template' is a char and 'ch' is an int to specify where in the char it will print.
But gcc does not look at template. it looks at 'ch' and thought it was int.

I don't know who's fault this is (gcc or me). Here is the code:
Code:

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

int main(void)
{
        char template[999] = "qwertyuiopasdfghjklzxcvbnm1234567890äåéëþüúíóö«»áßðø¶æ©®bñµç.¿¹²³¤^¥×¡,~_£¼½¾,~*÷ÄÅÉËÞÜÚÍÓÖÁ§ÐÏØÆ¢°®ÑµÇ";
        int ch;
        for (;;)
        {
                ch = rand() % strlen(template);
                printf("%s", template[ch]);
                fflush(stdout);
        }
        return 0;
}

I need it soon! THanks in advance.

Add '-Wall -Wextra' to your compilation command line and make sure there are zero warnings. You might need also '-O2' to activate yet more warnings, or consult 'gcc' documentation to see how 'printf' format string related warnings are activated.

I am telling you that you have type mismatch, and it's your challenge to understand why/where.

sundialsvcs 11-20-2012 08:31 PM

"%s" expects a pointer to a null-delimited string of characters.

But template[ch] is not that: it's a single (integer...) value consisting of one character taken from an array.

No wonder "C" is confused. The ASCII equivalent of, say, the letter "q", is probably not a valid pointer!

theNbomr 11-21-2012 01:16 PM

It is even worse than that. The value of template[ch] will always be the terminating null byte of the initializing literal string. So dereferencing it should result in a segmentation fault.
--- rod.


All times are GMT -5. The time now is 10:56 PM.