Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-4041-

Shit in C

Name: Anonymous 2009-02-25 10:09

I'm trying to set the contents of a string based on what random number is generated by my srand.

dice = rand() % 10 + 1;

if ( dice = 1 )
word[20] = "Success";

^-- this shit doesn't work, though.

tl;dr. I want my "dice rolls" to generate a random number, random number corresponds to a pre-set word, and the preset word to be printed.

I'm probably going about it the wrong way. Suggestions from experts?

Name: Anonymous 2009-02-25 10:14

if ( dice = 1 )
you're assigning dice to 1 all the time, so it'll print success all the time

I don't see any correct srand() call either

Name: Anonymous 2009-02-25 10:22

Sorry. I should've copied and pasted it.

srand ( time(NULL) );

ad = rand() % 6 + 1;

if ( ad == 1 )
word[20] = "Success";
if ( ad == 2 )
word[20] = "Failure";
if ( ad == 3 )

etc etc.

not sorted out all my possible values yet. before I go writing/copy pasting too much of that, I'd rather have it WORK.

Any idea why it won't work? It's saying "incompatible types in assignment"

Is there any more efficient way to do this?

Name: Anonymous 2009-02-25 10:23

Also, I did call all my variables earlier, etc.

char word[20]; 
int ad;

Name: case [...] of meme fan 2009-02-25 10:24

>>3
Try switch.

Name: Anonymous 2009-02-25 10:27

>>5
I'll look it up. :) thanks.

Name: case [...] of meme fan 2009-02-25 10:28

>>6
Be warned that it might not help you; but it will certainly make your code prettier.

Name: Anonymous 2009-02-25 10:35


     switch( expression )
     {
        case constant-expression1:    statements1;
        [case constant-expression2:    statements2;]   
        [case constant-expression3:    statements3;]
        [default : statements4;]
     }


^--- forgive me for being a massive faggot, but how exactly do I use this?

Where would my integer go? I'm just having difficulty understanding the syntax.

Name: Anonymous 2009-02-25 10:48

HJOly shit I am an EXPERT C PROGRAMMER that makes me rage.

You should be using a retard language

Name: Anonymous 2009-02-25 10:58

word[20] = "Success";

What is this ``word'' ? According to >>4 it's a character array/string then you're basically putting a pointer which got cast to a character ( so pointer & 0xFF ) into the 20th element/character(?) of the word array(or string?). This doesn't really make any sense. Maybe you want to just make ``word'' point to that string then simply write word = "that string"; It will make word point to the new string, also you would probably want to change that char word[20]; to char *word; since you want to be passing a pointer to the string, otherwise word will be preallocated on stack or locally or wherever you wrote that definition, alternatively you can use strcpy/memcpy/... to copy the string to your 20 character buffer... or maybe you should stop posting here and instead read K&R until you understand types( and pointers ) in C.

Name: Anonymous 2009-02-25 11:01

>>10

The latter seems a good idea. Thank you, though.

Name: Anonymous 2009-02-25 11:12

>>10
u raelly sounds like an EXPERT C PROGRAMMER...pointer cast to a character..are you crazy?

Name: Anonymous 2009-02-25 11:28

>>12
6. Compilers often give more memory to arrays than you asked for. Here's how to check how big an array actually is (memset returns a null pointer if the size you passed to it is bigger than the size of the array you passed to it):
int arr[256];
size_t realsize;
for (realsize = 0; realsize <= SIZE_MAX; ++realsize)
        if (!memset(arr, 0, realsize)) break;
/* now you know that arr actually has realsize / sizeof (int) elements */

If you combine this with #5, your program will be faster in the long run (but this usually doesn't work for short programs).

Name: Anonymous 2009-02-25 11:52

>>13
OH LAWDY

Name: Anonymous 2009-02-25 13:14

>>12
I was just saying what his code did, not if it makes sense. His code was casting a pointer to a character and writing it to an array, don't believe me? Here comes some proof:

- C file

void main(void)
{
    char a;
    char b[20];
    a = "test";
    b[20] = "loltext";
}

- Generated assembly for x86 target:

$SG34    DB    'test', 00H
    ORG $+3
$SG35    DB    'loltext', 00H
_DATA    ENDS
_TEXT    SEGMENT
_a$ = -4
_b$ = -24
_main    PROC NEAR
; File test.c
; Line 2
    push    ebp
    mov    ebp, esp
    sub    esp, 24                    ; 00000018H
; Line 5
    mov    eax, OFFSET FLAT:$SG34 ; eax contains pointer to 'test' string
    mov    BYTE PTR _a$[ebp], al ; al is the lower byte of eax, or pointer to 'test' & 0xFF as I said before.
; Line 6
    mov    ecx, OFFSET FLAT:$SG35 ; ecx contains pointer to 'loltext'
    mov    BYTE PTR _b$[ebp+20], cl ; cl is the lower byte of the pointer to 'loltext' (or just p & 0xFF ), and its written to b[20]
; Line 7
    mov    esp, ebp
    pop    ebp
    ret    0
_main    ENDP
_TEXT    ENDS
END


This is actually quite simple to understand, C will allow casting almost anything to anything you want, and the compiler will throw warnings when you do stupid stuff like that, but it won't forbid you to do it.

Example warnings:

test.c
test.c(5) : warning C4047: '=' : 'char ' differs in levels of indirection from 'char [5]'
test.c(6) : warning C4047: '=' : 'char ' differs in levels of indirection from 'char [8]'


I never said what OP was doing was correct in any way, i merely stated what his could would do when compiled/ran!

Now go back to reading that K&R book.

Name: Anonymous 2009-02-25 13:14

s/his could/his code/

Name: Anonymous 2009-02-25 13:18

To continue off that post,
a string will usually be statically allocated and passed as a pointer (which is usually no different when stored than an int for x86 platforms), now the OP tries to put an pointer into a character? The compiler will issue a warning(or error depending on options(how strict) used), and implicitly cast it to a char, which just does as was shown above.

Name: Anonymous 2009-02-25 14:38

>>15
yhbt

Name: Anonymous 2009-02-27 2:37

>>13
ANONIX QUALITY

Name: Anonymous 2011-12-30 9:31

>>19
ANuS

Name: Anonymous 2011-12-30 9:39

Here is how I would do it.

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

/* words[0] indicates failure
   words[1] indicates success */
char * words [] = {
  "failure",
  "success"
};

int main (void) {
  int i;
  int dice;

  srand(time(NULL));

  for (i = 0; i < 10; i++) {
    dice = rand() % 10 + 1;
    printf("%s: you rolled %d\n",
       words[dice == 1], dice);
  }

  return 0;
}

Name: kodak_gallery_programmer !!kCq+A64Losi56ze 2011-12-30 11:41

>>21
You do realize that random function really isn't random don't you? Wait, never mind. Don't answer that.

Name: Anonymous 2011-12-30 14:10

>>22
Yes and what is your point?
It doesn't interfere with the concept I was trying to illustrate.

Name: Anonymous 2011-12-30 16:23

>>13
memset returns a null pointer if the size you passed to it is bigger than the size of the array you passed to it
In PROPERLY BOUNDS-CHECKED C, memset() would signal a SIGSEGV if it exceeds the bounds of the array, which could then be caught.

Name: Anonymous 2011-12-30 17:32

char *words[3] = { "success", "failure", "desu" };

srand(time(NULL));
printf(words[rand() % 3]);

Name: Anonymous 2011-12-30 17:53

You can't do this:
char array[20];

array = "string";

You can do
char array[] = "string";
But you can't assign a string to an array that already exists:
[quote]$ cat >tmp.c
int main()     
{
    char array[20];
    array = "string";
    return 0;
}

$ cc tmp.c
tmp.c: In function ‘main’:
tmp.c:4:8: error: incompatible types when assigning to type ‘char[20]’ from type ‘char *’[/quote]

Name: Anonymous 2011-12-30 18:09

>>26
That's because a string literal is a character array, which behaves like a constant pointer except for sizeof and unary &.

Name: Anonymous 2011-12-30 18:20

>>27
I know, that's my point.

Name: kodak_gallery_programmer !!kCq+A64Losi56ze 2011-12-30 18:22

>>27
That's incorrect. Please try again.

Name: Anonymous 2011-12-30 19:02


[ Fri Dec 30 07:01:20 ]
[ @ ~/host/prog/sl ] $ cat sl.c
#include <stdio.h>
void main()
{
    const char space = ' ';
    const char nl = '\n';
    const char *psl[] = {
        "Fuck Kodak",
        "Fuck him in the anus",
        "Fuck him good"
    };
    char sl[] = "bodak is a fag";
    int i,j,len;
    sl[0] = 'k';
    len=sizeof(sl)/sizeof(char)-1;
    puts(sl);
    for(i=1;i<len-1;++i){
        putchar(sl[i]);
        for(j=0;j<len-2;++j)
            putchar(space);
        putchar(sl[len-1-i]);
        putchar(nl);
    }
    for(i=0;i<=len;++i)
        putchar(sl[len-i]);
    putchar(nl);
    puts(psl[0]);
    puts(psl[1]);
    puts(psl[2]);   
}
[ Fri Dec 30 07:01:25 ]
[ @ ~/host/prog/sl ] $ ./a.out
kodak is a fag
o            a
d            f
a            
k            a
             
i            s
s            i
             
a            k
             a
f            d
a            o
gaf a si kadok
Fuck Kodak
Fuck him in the anus
Fuck him good

Name: kodak_gallery_programmer !!kCq+A64Losi56ze 2011-12-30 19:05

>>30
That code won't even compile on my Linux or Windows box. And guess what you idiot? Both computers have an ANSI/ISO conformant C compiler!

Name: Anonymous 2011-12-30 19:16

>>31
Use a better/smarter compiler moron.


[ Fri Dec 30 07:10:24 ]
[ @ ~/host/prog/sl ] $ cat sl.c
#include <stdio.h>
void main()
{
    const char space = ' ';
    const char nl = '\n';
    const char *psl[] = {
        "Fuck Kodak",
        "Fuck him in the anus",
        "Fuck him good"
    };
    char sl[] = "bodak is a fag";
    int i,j,len;
    sl[0] = 'k';
    len=sizeof(sl)/sizeof(char)-1;
    puts(sl);
    for(i=1;i<len-1;++i){
        putchar(sl[i]);
        for(j=0;j<len-2;++j){
            if(j != i-1 && j != len-i-2)
                putchar(space);
            else if(j == i-1)
                putchar(sl[i]);
            else if(j == len-i-2)
                putchar(sl[len-i-1]);
        }
        putchar(sl[len-1-i]);
        putchar(nl);
    }
    for(i=0;i<=len;++i)
        putchar(sl[len-i]);
    putchar(nl);
    for(i=0;i<len;++i){
        for(j=0;j<=i;++j)
            putchar(sl[j]);
        for(j=i+1;j<len;++j)
            putchar(sl[len-j]);
        putchar(nl);
    }
    puts(psl[0]);
    puts(psl[1]);
    puts(psl[2]);   
}
[ Fri Dec 30 07:10:50 ]
[ @ ~/host/prog/sl ] $ gcc -std=c89 -pedantic sl.c
sl.c:2: warning: return type of ‘main’ is not ‘int’
[ Fri Dec 30 07:10:53 ]
[ @ ~/host/prog/sl ] $ ./a.out
kodak is a fag
oo          aa
d d        f f
a  a         
k   k    a   a
             
i     is     s
s     is     i
             
a   k    a   k
   a         a
f d        f d
ao          ao
gaf a si kadok
kgaf a si kado
koaf a si kado
kodf a si kado
koda a si kado
kodaka si kado
kodak  si kado
kodak isi kado
kodak isi kado
kodak is  kado
kodak is akado
kodak is a ado
kodak is a fdo
kodak is a fao
kodak is a fag
Fuck Kodak
Fuck him in the anus
Fuck him good
[ @ ~/host/prog/sl ] $ rm a.out
[ Fri Dec 30 07:14:44 ]
[ @ ~/host/prog/sl ] $ tcc sl.c
[ Fri Dec 30 07:14:46 ]
[ @ ~/host/prog/sl ] $ ls
a.out  sl.c

Name: kodak_gallery_programmer !!kCq+A64Losi56ze 2011-12-30 19:22

>>32
No sir. I don't use non standard C compilers. Now run along and go scrub another toilet you mental  midget.

Name: Anonymous 2011-12-30 19:25

Can i recommend using the filesystem?

btw This is something i made a while back... obviously doing a bit more than you need, and naming convention used is pretty terrible, but it's a start...

//-------------

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

//-----------------------------

const char cBlock[29] ={"!abcdefghijklmnopqrstuvwxyz'"};

const cBSize = 28;

struct s_chNode        {int_fast16_t ID, depth, extVal, byVal;};
struct s_uniNode    {int_fast16_t ID, extVal, byVal, wordBool;};

struct s_chNode *Blinks, *blink; // Base-Links
struct s_uniNode *Ulinks, *ulink; // Upper-Links

int iBlinkmax=0, iBlinks=0;
int iUlinkmax=0, iUlinks=0;

char *Buffer;

//-----------------------------

void initBlink(){
Blinks = (struct s_chNode *)malloc(sizeof(struct s_chNode));
}

//-----------------------------

void initUlink(){
Ulinks = (struct s_uniNode *)malloc(sizeof(struct s_uniNode));
}

//------------------------------

void incBlink(){
blink = realloc(Blinks,((iBlinkmax+=10)+2)* sizeof(struct s_chNode));
if (blink!=NULL) Blinks = blink;
}

//---------------------------------

void incUlink(){
ulink = realloc(Ulinks,((iUlinkmax+=10)+2)* sizeof(struct s_uniNode));
if (ulink!=NULL) Ulinks = ulink;
}

//------------------

int BlinkScan(int BPreV, int BVal){
int iB, iHalt=-1;
for(iB=0;iB<iBlinks;iB++){
    if(Blinks[iB].byVal == BVal)
        if(Blinks[iB].extVal == BPreV) return iB;
    }
return -1;
}

//-----------------------

int UlinkScan(int BPreV, int BVal){
int iB, iHalt=-1;
for(iB=0;iB<iUlinks;iB++){
    if(Ulinks[iB].byVal == BVal)
        if(Ulinks[iB].extVal == BPreV) return iB;
    }
return -1;
}

//-----------------------
   
int BlinkEntry(int iD, int PreVal, int Val, int deep){
int iB=0;
iB = BlinkScan(PreVal, Val);
  if (iB!=-1) return iB;
if(iBlinkmax<=iD) incBlink();
Blinks[iD].ID = iD;
Blinks[iD].depth = deep;
//Blinks[iD].Index = 0;
Blinks[iD].extVal = PreVal;
Blinks[iD].byVal = Val;
//Blinks[iD].branch = 0;
//Blinks[iD].leaf = 0;
iBlinks++;
//printf("added %i", iBoards-1);
return iD;
}

//------------------

int UlinkEntry(int iD, int PreVal, int Val){
int iB=0;
iB = UlinkScan(PreVal, Val);
  if (iB!=-1) return iB;
if(iUlinkmax<=iD) incUlink();
Ulinks[iD].ID = iD;
//Ulinks[id].depth = deep;
//Blinks[iD].Index = 0;
Ulinks[iD].extVal = PreVal;
Ulinks[iD].byVal = Val;
//Ulinks[iD].branch = 0;
//Ulinks[iD].leaf = 0;
Ulinks[iD].wordBool = 0;
iUlinks++;
//printf("added %i", iBoards-1);
return iD;
}

//---------------------------

int scanChar(int cX){
  int Geti=0, Seti=0;
  while(Geti<=cBSize){
    if((int) cBlock[Geti]==cX) Seti = Geti;
    Geti++;
    }
  return Seti;
}

//------------------------------



int mainBuff(char *Fin, char *Fout){

FILE *file;
char *name;
unsigned long fX=0, fileLen=0;
int OutLen=0;
printf("open..");
file = fopen(Fin, "rb+");
if (!file){
    printf("...File not found, using string %s\n", &Fin[0]);
    return 0;
    }
printf("seek..");
fseek(file, 0, SEEK_END);
printf("tell..");
fileLen = ftell(file);
printf("seek..");
fseek(file, 0, SEEK_SET);
printf("malloc..");
Buffer = (char *)malloc(fileLen+1);
if (!Buffer){
    printf("Mem Failed!!");
    fclose(file);
    return -1;
    }
printf("read..");
fread(Buffer, fileLen, 1, file);
printf("close..");
fclose(file);
OutLen = (int) fileLen;
//l_KeepVal = OutLen;
printf("-%i- \\n\n",(int) OutLen);
//printf("%s", &Buffer[0]);
return OutLen;
}

//----------------------------------

int Getstr(int Ui){
int i=0, x=Ui, z=0, gint=0;
char gotstr[50], cvar;
while(x!=0){
    z=Ulinks[x].byVal;
    while(z!=0){
        gotstr[gint] = cBlock[Blinks[z].byVal];
        gint++;
        //printf("%c", cBlock[Blinks[z].byVal]);
        z = Blinks[z].extVal;
        }
    gotstr[gint]=0;
    x=Ulinks[x].extVal;
    }
gint--;
for(i=0;i<gint;i++, gint--){
    cvar = gotstr[gint];
    gotstr[gint] = gotstr[i];
    gotstr[i] = cvar;
    }

printf("%s ", &gotstr[0]);
return 0;
}

//----------------------------------


int main(int argc, char *argv[]){
  char  *myStr;
  int i=0, j=1, k=0, l=0, m=0, loopi=0, li=0, Ui=0, n=0;

  initBlink();
  BlinkEntry(iBlinks, 0, 0, 0);
  initUlink();
  UlinkEntry(iUlinks, 0, 0);

  if(argc>=2){
    if((loopi=mainBuff(argv[1], myStr))<=0){
        loopi = strlen(argv[1]);
        myStr = (char *)malloc(loopi+1);
        for(li=0;li<=loopi;li++){
            myStr[li] = argv[1][li];
            }
        } else {
        myStr = (char *)malloc(loopi+1);
        for(li=0;li<=loopi;li++){
            myStr[li] = Buffer[li];
            }
        free(Buffer);
        }
    printf("//%i//\n", loopi);
    } else {
        printf("%s: Usage: 'Insert string or filename here' \n\n", argv[0]);
        return 0;
    }
  li=0;
  while(((int) j!=0)+(i<=loopi)==2){
    j= (int) myStr[i];

    //printf("%i %i %i\n", (int)'A', (int)'Z', ((int)'a') - ((int)'A'));
    if((j>=65)+(j<=90)==2) j+=32;

    //k=scanChar(j);
    k=scanChar(j);
   

    if(li==-1){
        n=k;
        k=0;
        }
    if(k==0){
        //printf("::Ui %i <-", Ui);
        Ui=UlinkEntry(iUlinks, Ui, m);
        //printf("::Ui [%i] %i::\n", Ui, m);
        li=0;
        l=0;
        m=0;
        //n=0;
        if(n==0){
            Ulinks[Ui].wordBool=1;
            Ui=0;
            }
           
        }
    //printf("-%c -", j);
    if(n!=0){
        k=n;
        n=0;
        }
    if(k!=0){
        li++;
         m=BlinkEntry(iBlinks, l, k, li);
        /*printf("%i-%c-%i-%i [%i]", l, cBlock[k], m, i, li);*/
        if(li==3) li=-1;
        l=m;
        }
    //printf("\n");
    i++;
    }
  li=0;
  printf("String Dump\n\n");
  for(i=1;i<iUlinks;i++){
    if(Ulinks[i].wordBool==1){
        Getstr(i);
        //printf("\n");
        li++;
        }
    }
  printf("\n\n%i Words, %i lo-Nodes, %i hi-Nodes\n\n", li, iBlinks, iUlinks);
  return 0;
}

//--------------

Name: Anonymous 2011-12-30 19:25

>>33
you're a moron, enjoy your shitty compiler that's not even smart enough to convert a void main to int main and return 0 at the end.

Name: Anonymous 2011-12-30 19:29

>>35
IT'S CALL STANDARD C YOU FUCKING MORON. I DON'T KNOW IF YOU KNOW THIS OR NOT, BUT C IS MEANT TO BE PORTABLE. THAT FUCKING MEANS A COMPILER MUST FOLLOW CERTAIN STANDARDS TO ENSURE PORTABILITY.

NO GO SCRUB ANOTHER TOILET YOU FUCKING DUMB JEW.

Name: Anonymous 2011-12-30 19:31

>>36
you forgot your trip kodak fag.
gcc is portable.

Name: Anonymous 2011-12-30 19:32

>>37
OH MY BAD. I FORGOT TO USE THE "YOUR A FUCKING MORON" FLAG.

Name: kodak_gallery_programmer !!kCq+A64Losi56ze 2011-12-30 19:34

>>38

3/10

Name: Anonymous 2011-12-30 19:34

>>38
I can tell you're angry by the forced capitalization of all words. It's ok we know you're retarded. The faster you understand this the faster we can help you.

Name: Anonymous 2011-12-30 19:37

34>>

Nested-trie dictionary implementation, with the capacity to slurp up new words from random text files passed via cmdline...

I was just feeding it random webpages so it could learn lots of words cheaply

...Crazy trying to hard-code words you want to use

Name: Anonymous 2011-12-30 20:44

>>40
eat shit and die, lisp-advocating scumbag

Name: Anonymous 2011-12-30 20:51

Probably a bad example for someone who is new to coding though..

In turbo pascal (or most any language =D) you could just use a readline / writeline to store & load words from a text file... then just pick words (/lines from the file) at random, and print to screen...

might only need 20-30 lines of turbo to get it to work

Name: Anonymous 2011-12-30 23:10

...back to basics


Word[1]='S';
Word[2]='u';
Word[3]='c';
Word[4]='c';
Word[5]='e';
Word[6]='s';
Word[7]='s';
Word[8]=(char) 0;

printf("%s \n", &Word[1]);

Name: Anonymous 2011-12-31 2:46

Lol u all a bunch of dumb niggers posting in a 2 year old thread

Name: Anonymous 2011-12-31 2:57

>>44'
starting at 1
printing a char with printf
using %s on a char


IHBT

Name: Anonymous 2011-12-31 4:41

>>46
You're a moron.

Name: Anonymous 2011-12-31 4:43

>>47
%p

Name: Anonymous 2011-12-31 4:51


1 Name: Anonymous : 2009-02-25 10:09

Name: Anonymous 2011-12-31 4:52

>>49
Yes we know, what is your point?

Name: Anonymous 2011-12-31 5:15

...back to (even more) basic's

Word[2]='S';
Word[3]='u';
Word[4]='c';
Word[5]='c';
Word[6]='e';
Word[7]='s';
Word[8]='s';
Word[9]=(char) 0;

printf("%s \n", &Word[2]);


...And it still prints "Success (\n)"...

...poor anon had to wait 3 whole yrs ^^

Name: Anonymous 2011-12-31 5:28

>>51

printf("%s \n", &Word[2]);

prints
uccess (\n)

Name: Anonymous 2011-12-31 5:54

>>52

did you re-copy the whole code, or just the printf?

(Notice it now starts at 2 for both [Word[2]='S';] & [printf("%s \n", &Word[2]);])

=( this isn't really making up for being stuck at home on new years....

Name: Anonymous 2011-12-31 6:27

>>53
Oh ic, i derped.

Name: DUBS LIBERATION FRONT 2012-03-24 18:32

NON-DUBS SHALL BE CLEANSED FROM THE EARTH!

Name: Anonymous 2012-03-25 9:40

>>48
You're a moron.

Don't change these.
Name: Email:
Entire Thread Thread List