compare pointer and integer?

This is a discussion on compare pointer and integer? within the C Programming forums, part of the General Programming Boards category; hello, everyone! i'm trying something in c. so far i've done a program like this: Code: #include<string.h> #include<stdio.h> char search_string[100]="

  1. #1
    Registered User nyekknyakk's Avatar
    Join Date
    Aug 2010
    Posts
    35

    compare pointer and integer?

    hello, everyone!
    i'm trying something in c.
    so far i've done a program like this:
    Code:
    #include<string.h>
    #include<stdio.h>
      char search_string[100]="\0";
      char *array[50];
      int loop;
    
    int main(void)
    {
      while(1){
      printf("\n>>");
      gets(search_string);
    
      array[0]=strtok(search_string," ");
      if(array[0]==NULL)
       {
        printf("Error.\n");
        exit(0);
       }
    
      for(loop=1;loop<50;loop++)
       {
        array[loop]=strtok(NULL," ");
       }
       
          	if (strcmp(array[0], "A")==0) {
          		printf("%s\n", array[0]);
          		if (strcmp(array[1], "B")==0)
          			printf("%s", array[1]);
          		else if (strcmp(array[1], "C")==0)
          			printf("%s", array[1]); 
          		else printf("x"); }
          	else if (strcmp(array[0], "D")==0)
          		printf("%s\n", array[0]);
    	}
    }
    now, what i'm planning to do is to give the user the ability to input an integer.
    i'm wondering how to do that since everytime i try to put
    Code:
    if (array[1] = 2)
    the compiler says that ANSI C++ forbids comparison between pointer and integer.
    What shall I do to be able to get both letters and numbers from the user.

    My program(so far):
    >>A B
    A
    B
    >>A C
    A
    C
    >>D
    D

    My target program:
    >>A B
    A
    B
    >>A 1
    A
    1
    >>2
    2

    Thanks!

  2. #2
    Registered User Char*Pntr's Avatar
    Join Date
    Sep 2007
    Location
    Lathrop, CA
    Posts
    198

    Smile Try this

    First, I'm assuming that in your snip is a typo:

    Code:
    if (array[1] = 2)
    I think you meant to write:

    Code:
    if (array[1] ==2)
    Now for the problems at hand...

    Try a typecast in front of array[1]:

    Code:
    if (  (int *) array[1]  ==2 )
    I've found using Typecast very useful for problems
    just like you described.
    Last edited by Char*Pntr; 08-18-2010 at 11:39 AM.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,941
    Quote Originally Posted by Char*Pntr
    I've found using Typecast very useful for problems
    just like you described.
    On the contrary, nyekknyakk, casting array[1] to int* is the wrong thing to do here. Rather, I notice that you are already using strcmp to compare say, array[1] with "A". You can use it to compare array[1] with "2".

    At a glance, there are a few other things you could improve:
    • Make your indentation more consistent.
    • #include <stdlib.h> if you really want to use the exit function.
    • Avoid global variables.
    • Replace the use of gets with say, fgets.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User nyekknyakk's Avatar
    Join Date
    Aug 2010
    Posts
    35
    i tried Char*Pntr's suggestion but it didn't work..
    but still thanks for the reply!

    laserlight, are you saying that i can compare array[1] with an integer?
    Code:
    if(strcmp(array[1], 2)==0)
    my compiler said that passing `int' to argument 2 of `strcmp(const char *, const char *)' lacks a cast and incompatible types in assignment of `int' to `char[100]'..

    i'm sorry for my indentations, i'm still not used to it.
    i also forgot about stdlib.h, i'm using global variables right now because the program i'm working on has a lot of functions. why should i avoid global variables?
    and also, i still don't know how fgets is used. i'm still learning the basics>
    thanks!

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,941
    Quote Originally Posted by nyekknyakk
    laserlight, are you saying that i can compare array[1] with an integer?
    Yes, except that this integer is actually a string
    Code:
    if(strcmp(array[1], "2") == 0)
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User nyekknyakk's Avatar
    Join Date
    Aug 2010
    Posts
    35
    Quote Originally Posted by laserlight View Post
    Yes, except that this integer is actually a string
    Code:
    if(strcmp(array[1], "2") == 0)
    but my compiler says: incompatible types in assignment of `int' to `char[100]'?
    i don't understand what that means?

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,941
    What exactly did you write?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User nyekknyakk's Avatar
    Join Date
    Aug 2010
    Posts
    35
    you mean my whole code?
    Code:
    #include<string.h>
    #include<stdio.h>
    #include<stdlib.h>
      char search_string[100]="\0";
      char *array[50];
      int loop;
    
    int main(void)
    {
      while(1){
      printf("\n>>");
      gets(search_string);
      
      if(search_string = 1)
      	printf("HI!");
    
      array[0]=strtok(search_string," ");
      if(array[0]==NULL)
       {
        printf("Error.\n");
        exit(0);
       }
    
      for(loop=1;loop<50;loop++)
       {
        array[loop]=strtok(NULL," ");
       }
       
          	if (strcmp(array[0], "A")==0) {
          		printf("%s\n", array[0]);
          		if (strcmp(array[1], "B")==0)
          			printf("%s", array[1]);
          		else if (strcmp(array[1], "C")==0)
          			printf("%s", array[1]); 
          		else printf("x"); }
          	else if (strcmp(array[0], "D")==0)
          		printf("%s\n", array[0]);
       		else if(strcmp(array[1], "2") == 0)
       			printf("%s", array[1]);
    	}
    }
    what seems to be the problem?

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,941
    Quote Originally Posted by nyekknyakk
    what seems to be the problem?
    Along with the error message should come a line number. In this case, the error message indicates that the error was detected on line 14 (but note that the error could actually be elsewhere; it was merely detected on this line). We see:
    Code:
    if(search_string = 1)
    What exactly are you trying to do by assigning 1 to search_string? Perhaps you mean to compare search_string with 1, but that still does not make much sense.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User nyekknyakk's Avatar
    Join Date
    Aug 2010
    Posts
    35
    oh.. where did that came from?
    finally, now it compiled!
    i was really focusing on line 14, i didn't notice this simple mistake.
    i'm sorry about that and thank you very much!

    edit:
    but there seems to be another problem, whenever i run the program,
    if i typed A alone, it crashes and stops, why is that happening?
    Last edited by nyekknyakk; 08-18-2010 at 12:27 PM.

  11. #11
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    455
    You declared 'array' as an array of 50 pointer-to-char, so array[i] is a pointer. when you write:
    Code:
    if (strcmp(array[0], "A")==0
    array[0] is a pointer. You can't compare a pointer and a string.
    I think you actually meant:
    Code:
    char *array
    which will work. if you do so, remove the for loop and replace it with:
    Code:
     char *array
     array = strtok(search_string," ,");
     while (array != NULL)
       {
         printf("%s\n", array);
         array = strtok(NULL," ,");
       }
    Last edited by nimitzhunter; 08-18-2010 at 04:04 PM.

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,941
    Quote Originally Posted by nyekknyakk
    but there seems to be another problem, whenever i run the program,
    if i typed A alone, it crashes and stops, why is that happening?
    It might be a good idea to post the current version of your code.

    Quote Originally Posted by nimitzhunter
    You can't compare a pointer and a string. (...) which will work.
    It is true that it does not normally make sense to compare a pointer and a string, but here strcmp is used to compare the string whose first element is pointed to by the pointer, with a string literal. Other than possible problems with what array[0] points to, it is perfectly fine.

    In fact, taking your suggestion of changing array to be a pointer to char is wrong: you would then be trying to use strcmp to compare a lone char with a string. If instead we use strcmp(array, "A"), it would then be "comparing a pointer and a string", using your phrasing.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User nyekknyakk's Avatar
    Join Date
    Aug 2010
    Posts
    35
    there has been a lot of changes in my program, recently. i'm now working on a program which lets the user make and display a matrix.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    void make_mat();
    char cmd_str[50]="\0";
    char *array[50];
    char get_cmd();
    int mat_A[50][50], mat_B[50][50], mat_C[50][50];
    int r1, c1, r2, c2, r3, c3, i, j; 
    int loop;
    
    int main()
    {                 
    	while(1)
    	{
    		get_cmd();
    		if (strcmp(array[0], "MAKE")==0)
    				make_mat();
    		else if (strcmp(array[0], "DISP")==0)
    				printf("DISP");
    		else	
    				printf("Invalid Command!");			
    	}
    } 					
    
    /*Get Command Function*/
    char get_cmd()
    {
    	printf("\n>>");
    	gets(cmd_str);
    	
       array[0]=strtok(cmd_str," ");
       if(array[0]==NULL)
       {
       	printf("Error.\n");
       }
       
       for(loop=1;loop<50;loop++)
       	array[loop]=strtok(NULL," ");
       	
    	return (*array[0]);
    }
    
    /*Make Function*/
    void make_mat()
    {
    	if (strcmp(array[1], "A")==0)
    	{
    		printf("Enter rows: ");
          scanf("%d", &r1);
          printf("Enter columns: ");
             		scanf("%d", &c1);
             		for(i=0;i<r1;i++)
             			for(j=0;j<c1;j++)
             			{
             				printf("A[%d][%d] = ", i, j);
             				scanf("%d",&mat_A[i][j]); 
             			}
    	}
    	else if (strcmp(array[1], "B")==0)
    	{
    		printf("Enter rows: ");
          scanf("%d", &r2);
          printf("Enter columns: ");
             		scanf("%d", &c2);
             		for(i=0;i<r2;i++)
             			for(j=0;j<c2;j++)
             			{
             				printf("A[%d][%d] = ", i, j);
             				scanf("%d",&mat_B[i][j]); 
             			}
    	}
    	else if (strcmp(array[1], "C")==0)
    	{
    		printf("Enter rows: ");
          scanf("%d", &r3);
          printf("Enter columns: ");
             		scanf("%d", &c3);
             		for(i=0;i<r3;i++)
             			for(j=0;j<c3;j++)
             			{
             				printf("A[%d][%d] = ", i, j);
             				scanf("%d",&mat_C[i][j]); 
             			}
    	}
    }
    there, but now, it has 2 problems:

    a. if the user only typed MAKE, the program will immediately crash.
    Code:
    >>MAKE
    -will crash
    b. if the user typed MAKE A, it is fine. but, after completing the matrix(filling the rows), the program will print >>Error then, immediately crash.
    Code:
    >>MAKE A
    Enter row: 2
    Enter column: 2
    A[0][0] = 1
    A[0][1] = 2
    A[1][0] = 3
    A[1][1] = 4
    
    >>Error.
    -also crashes

    New_Ink2001 told me that i should try moving the loop for tokenizing so that it is not run when get_cmd decides it's got an error or perhaps avoid tokenizing the string entirely if it is empty because strtok and gets are both somewhat misfits.
    how should i do that?
    Last edited by nyekknyakk; 08-19-2010 at 12:47 AM.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,941
    First, we need to indent the code properly. Then, change the global variables into local variables. You would notice a few patterns when this is done. I have purposely made mat_A, mat_B and mat_C local to certain if statements in make_mat. You actually should not do this, but I am doing this to demonstrate how your use of global variables has caused you to duplicate code needlessly:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    void make_mat(void);
    char get_cmd(void);
    
    char *array[50];
    
    int main(void)
    {
        while (1)
        {
            get_cmd();
            if (strcmp(array[0], "MAKE") == 0)
                make_mat();
            else if (strcmp(array[0], "DISP") == 0)
                printf("DISP");
            else
                printf("Invalid Command!");
        }
    }
    
    /*Get Command Function*/
    char get_cmd(void)
    {
        char cmd_str[50] = "\0";
        int loop;
    
        printf("\n>>");
        gets(cmd_str);
    
        array[0] = strtok(cmd_str, " ");
        if (array[0] == NULL)
        {
            printf("Error.\n");
        }
    
        for (loop = 1; loop < 50; loop++)
            array[loop] = strtok(NULL, " ");
    
        return *array[0];
    }
    
    /*Make Function*/
    void make_mat(void)
    {
        int i, j;
    
        if (strcmp(array[1], "A") == 0)
        {
            int mat_A[50][50];
            int r1, c1;
    
            printf("Enter rows: ");
            scanf("%d", &r1);
            printf("Enter columns: ");
            scanf("%d", &c1);
            for (i = 0; i < r1; i++)
                for (j = 0; j < c1; j++)
                {
                    printf("A[%d][%d] = ", i, j);
                    scanf("%d", &mat_A[i][j]);
                }
        }
        else if (strcmp(array[1], "B") == 0)
        {
            int mat_B[50][50];
            int r2, c2;
    
            printf("Enter rows: ");
            scanf("%d", &r2);
            printf("Enter columns: ");
            scanf("%d", &c2);
            for (i = 0; i < r2; i++)
                for (j = 0; j < c2; j++)
                {
                    printf("A[%d][%d] = ", i, j);
                    scanf("%d", &mat_B[i][j]);
                }
        }
        else if (strcmp(array[1], "C") == 0)
        {
            int mat_C[50][50];
            int r3, c3;
    
            printf("Enter rows: ");
            scanf("%d", &r3);
            printf("Enter columns: ");
            scanf("%d", &c3);
            for (i = 0; i < r3; i++)
                for (j = 0; j < c3; j++)
                {
                    printf("A[%d][%d] = ", i, j);
                    scanf("%d", &mat_C[i][j]);
                }
        }
    }
    I did not turn array into a local variable as this would mean that I would be doing quite a bit of surgery on your program that you should be doing. array is more of a list of command words extracted from the command entered by the user, so perhaps you should rename it to command_words.

    Now, the problem that you currently face is that command_words is an array of 50 pointers to char. This is fine, except it means that you have not allocated any space for each command word. Rather, the result that you get from strtok should be copied into an array of char. This means that you either use dynamic memory allocation with this pointer to char, or you say, change command_words to be an array of 50 arrays of char.

    Once you do this, the next step is to make make_mat independent of command_words. make_mat (rename it to make_matrix?) should make a matrix, rather than make matrix A, B or C, depending on the user input. If you do it this way, you only need to test that make_mat works, then you can use it later to make matrix D, E and F, etc.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,791
    Perhaps you should change
    gets(cmd_str);
    to
    fgets(cmd_str, sizeof(cmd_str), stdin)
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help assignment due tomorrow
    By wildiv in forum C Programming
    Replies: 6
    Last Post: 01-27-2010, 07:38 PM
  2. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  3. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-20-2009, 11:37 PM
  4. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 05:55 PM
  5. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21