Thread: Suggestions for improving.

  1. #16
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    Quote Originally Posted by matsp View Post
    But I do agree that arrays and pointers aren't the same thing. An array IS some memory, a pointer is a variable that holds an address of some memory.

    --
    Mats
    That's entirely incorrect.

    Arrays are essentially equal to pointers. Arrays aren't "memory" any more than pointers are addresses. Only difference between arrays and pointers is that arrays' memory is allocated on the stack while malloc()'ed memory will be allocated on the heap.

    But they are essentially the same because they simply point to allocated memory. Uninitialized pointers can point anywhere, including read-only memory, which is pretty much why using uninitialized pointers for strings is bad - Writing to read-only memory = Seg fault + crash.

  2. #17
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    I think matsp's statement was referring to how arrays and pointers have some semantic differences. For example, you can't increment arrays.

    Writing to read-only memory = Seg fault + crash
    Not necessarily. In programs compiled with Turbo C, when you dereference NULL, you get a message like "NULL pointer dereference" or something similar, and the program continues executing. You'll usually get a segmentation fault, but not all of the time.

    [edit] Ah yes, it was "NULL pointer assignment".

    But they are essentially the same because they simply point to allocated memory.
    Pointers are a little more flexible on this point, because you can have pointers pointing to the middle of arrays or dynamically allocated memory chunks. [/edit]
    Last edited by dwks; 09-05-2007 at 02:39 PM.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #18
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    At the hardware level and to the computer, arrays and pointers are more or less the same thing: contiguous blocks of memory that we reference usually by the address of the first element.

    Now in C, there are times that arrays and pointers are considered explicitly different, at least to the compiler. You can say they are the same, but the compiler will not always agree.

    TBH, if you understand why the compiler is throwing a fit and you understand the true difference between arrays and pointers, to interchange them when you know what you're doing isn't really a problem. Again, it's all provided you know what's going on.

  4. #19
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    Quote Originally Posted by dwks View Post
    I think matsp's statement was referring to how arrays and pointers have some semantic differences. For example, you can't increment arrays.


    Not necessarily. In programs compiled with Turbo C, when you dereference NULL, you get a message like "NULL pointer dereference" or something similar, and the program continues executing. You'll usually get a segmentation fault, but not all of the time.

    [edit] Ah yes, it was "NULL pointer assignment".


    Pointers are a little more flexible on this point, because you can have pointers pointing to the middle of arrays or dynamically allocated memory chunks. [/edit]
    What arrays are, basically, are simplified versions of pointers.

    Code:
    #include <stdio.h>
    
    int main(void)
    {
        char array[] = {"String"}, *ptr = array;
        
        printf("*(ptr+3) = %c\n"
               "array[3] = %c", *(ptr+3), array[3]);
               
        return 0;
    }
    We both know what that code prints. Like the above poster said, on hardware level, both are just contiguous blocks of memory in the program's address space - It's only C which differentiates.

  5. #20
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by IceDane View Post
    What arrays are, basically, are simplified versions of pointers.
    No, that's not correct. The C-compiler can make a pointer from an array, and you can use array syntax to access elements from a pointer, but an array and a pointer are semantically different, even if there is little difference in syntax. As I said earlier, an array declaration forms a piece of memory that the program can use to store/retrieve data from. A pointer contains some memory address - which of course could be an array, like in your example below - the ptr variable is set to the address of array (same as &array[0] - the compiler essentially allows this shortened form, because it's a very common way to do things).
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        char array[] = {"String"}, *ptr = array;
        
        printf("*(ptr+3) = %c\n"
               "array[3] = %c", *(ptr+3), array[3]);
               
        return 0;
    }
    We both know what that code prints. Like the above poster said, on hardware level, both are just contiguous blocks of memory in the program's address space - It's only C which differentiates.
    Of course, everything is memory in a computer, and it's just a question of how you use the memory. But if we look at it from a assembler standpoint, you have
    Code:
    array: db "String",0
    pptr:   dw array    // renamed to make it easier to follow, since ptr is a keyword in MASM
    fmt:    db "*(ptr+3) = %c\narray[3] = %c", 0
    ...
         mov eax, offset array
         push byte ptr [eax+3]
         mov eax, dword ptr pptr
         push byte ptr [eax+3]
         push offset fmt
         call   printf
    Now, that's not exactly the same thing, is it? It just gives the same result.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #21
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    Quote Originally Posted by matsp View Post
    No, that's not correct. The C-compiler can make a pointer from an array, and you can use array syntax to access elements from a pointer, but an array and a pointer are semantically different, even if there is little difference in syntax. As I said earlier, an array declaration forms a piece of memory that the program can use to store/retrieve data from. A pointer contains some memory address - which of course could be an array, like in your example below - the ptr variable is set to the address of array (same as &array[0] - the compiler essentially allows this shortened form, because it's a very common way to do things).


    Of course, everything is memory in a computer, and it's just a question of how you use the memory. But if we look at it from a assembler standpoint, you have
    Code:
    array: db "String",0
    pptr:   dw array    // renamed to make it easier to follow, since ptr is a keyword in MASM
    fmt:    db "*(ptr+3) = %c\narray[3] = %c", 0
    ...
         mov eax, offset array
         push byte ptr [eax+3]
         mov eax, dword ptr pptr
         push byte ptr [eax+3]
         push offset fmt
         call   printf
    Now, that's not exactly the same thing, is it? It just gives the same result.

    --
    Mats
    Only thing you've proven is arrays have more restrictions than pointers. Pointers can substitute arrays in any situation, even though arrays can't substitute pointers in some situations.


    And oh, by the way, did you try your code out? I'm a bit rusty in assembler, but aren't you dereferencing ptr one times too many? Wouldn't the following be sufficient?

    Code:
    mov eax, dword pptr
    push byte ptr [eax+3]
    I think you're trying to prove that arrays are different from pointers from a coding perspective while I'm trying to prove they're the same in memory(Which would essentially mean they're the same).

    If you take a pointer and an array, and print their hexadecimal values, you'll get addresses for both. Why? Because the first element of the array is simply the address of the allocated memory, and subsequent elements are simply the memory address incremented respectively. Arrays are simply an attempt to simplify string handling in C - They are still exactly the same as pointers when it comes to memory.

  7. #22
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  8. #23
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by IceDane View Post
    If you take a pointer and an array, and print their hexadecimal values, you'll get addresses for both. Why? Because the first element of the array is simply the address of the allocated memory, and subsequent elements are simply the memory address incremented respectively. Arrays are simply an attempt to simplify string handling in C - They are still exactly the same as pointers when it comes to memory.
    No, arrays are a way to statically (or semi-statically, in the case of local variables inside functions) to allocate memory for something. Pointers are a way to refer to things that are allocated in memory. There is a difference.

    By the way, arrays are used for a lot of things that aren't strings, although I would agree that strings are the most common case. But you can have arrays of structs, classes (assuming C++), and of course multidimensional arrays.

    I think you have it back to front - pointers are made to look like arrays, because it makes life easier dealing with pointers that way.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #24
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > Pointers can substitute arrays in any situation,
    How wrong can you be?
    Code:
    int main() {
        int arr[] = { 1, 2, 3, 4, 5 };
        int *p = { 1, 2, 3, 4, 5 };
        return 0;
    }
    The second one will get you a face-full of errors.
    Read the C.L.C FAQ link Dave pointed out to you.

    > The C-compiler can make a pointer from an array
    Except in some special cases - the first being the one I've just posted.

    The second is when you use sizeof().
    sizeof(array) and sizeof(ptr) give very different answers.

    There is a 3rd exception, which I'll leave you to discover by reading the FAQs
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #25
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    Looks like the topic was very essential to be opened.I am happy for that. I can make a statement too I think.There is a difference. Because arrays dont really act like a pointer.
    Code:
    #include <stdio.h>
    
    int main(void)
    {
     char a[6]="naber";
    	a=&a[3];
    	printf("&#37;s",a);
        return 0;
    }
    This code gives error. Unlike :
    Code:
    #include <stdio.h>
    
    int main(void)
    {
     char *a="naber";
    	a=&a[3];
    	printf("%s",a);
        return 0;
    }
    This code however, does not give error. In my opinion , the arrays just act in resemblence with pointers. Because in order to change the adress of string (assume it is an array) we have to use it as &string[0]. I may be looking to the case simply. But I have been thinking this way. If I am wrong please clarify me. By the way , here is the code of the program which counts each different word in a sentence:

    Code:
    #include <stdio.h>
    #include <string.h>
    void sayac(char *,char *,int,int *);
    int main()
    {
    struct str {
    		char d[10];
    	} st[8];
    char s[80];
    char kopya[80];
    	gets(s);
    	sprintf(kopya,"%s",s);
    	char *b;
    	b=strtok(s," ");
    	int x=0;
    	int i=0;
    	for(i=0;i<8;i++) {
    	
              x+=1;
    		sprintf(st[i].d,"%s",b);
    				b=strtok(NULL," ");
    		
    		if(b==NULL) break; }
      int y=0;
    	int k=0;
    	int control=0;
    	int p=0;
        for(i=0;i<x;i++) {
        for(k=0;k<i;k++)
    			if((strcmp(st[i].d,st[k].d))==0) control=1;
    		if(control==1) continue;
     y=strlen(st[i].d);
    		sprintf(s,"%s",kopya);
    		
    		sayac(s,&(st[i].d[0]),y,&p);
                  
    		printf("%s den %d tane var\n",st[i].d,p);
     p=0;     
    		
    		}
    return 0;
    }           
    
    		
    
    	void sayac(char *ana,char *str,int t,int *ptr) {
    		if(strstr(ana,str)==NULL) return;
    		else {
    			ana=strstr(ana,str);
    			*ptr=*ptr+1;
    			sayac(&ana[t],str,t,ptr); }
    	}
    Sorry for the mess of code lines. This is the way I write.

    Thank you for every response. =) By the way that post someone posted which leads us to another site , actually explains what I knew. That is true isnt that?
    Last edited by ozumsafa; 09-06-2007 at 08:52 AM.

  11. #26
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129

  12. #27
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    A few improvements, mostly style, but also efficiency.

    Code:
        for(i=0;i<x;i++) {
        for(k=0;k<i;k++)
    			if((strcmp(st[i].d,st[k].d))==0) control=1;
    		if(control==1) continue;
    if (!control) {
     y=strlen(st[i].d);
    		sprintf(s,"%s",kopya);
    		
    		sayac(s,&(st[i].d[0]),y,&p);
                  
    		printf("%s den %d tane var\n",st[i].d,p);
     p=0;    
    } 
    		
    		}
    Once control is one, it will stay one for forever. I suspect you want to reset it to zero someplace.

    Code:
             int y = 0;   // Remove the whole line. 
    ....
             sayac(s,&(st[i].d[0]),&p);   // Remove y
    ....
    	void sayac(char *ana,char *str,int *ptr) {
    		ana=strstr(ana,str);
    		if(ana) {
    			(*ptr)++;
    			sayac(ana,str,ptr); 
                    }
    	}
    This avoids calling strstr twice for no reason at all, and simplifies the if-statement (removes the else-part). the variable t is not used, (y is never changed in the calling code, and y is set to zero, so no reason to pass it.



    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  13. #28
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    I dont know if I misunderstood but if you do that , you will always find the same str in ana string.

    Yes I wanted to make control zero , but I copy pasted the codes. Sorry for that.

    And PLEASEEE , I know getss fgetss FAQQ!!!

  14. #29
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by ozumsafa View Post
    I dont know if I misunderstood but if you do that , you will always find the same str in ana string.
    Ok, if you say so. You still shouldn't have to do strstr twice, which ever way you do it.
    Yes I wanted to make control zero , but I copy pasted the codes. Sorry for that.

    And PLEASEEE , I know getss fgetss FAQQ!!!
    So, if you know how to do it correctly, why isn't your code showing that.

    And it would be easier for us to understand what's going on if:
    1. The language of printf() and such is English - I know, it's not your native language, neither is it mine (although I do admittedly live in England, and have done so for several years).
    2. If you make sure the indentation is correct when posted - it looks like your code has a mixture of spaces and tabs. Tabs aren't necessarily the same width in all applications, so it's best if you can replace them with spaces. [Most editors have a way to replace tabs with spaces all automaticaly].

    I presume you do want to learn from this.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Suggestions and question about bool pointers
    By Akkernight in forum C++ Programming
    Replies: 15
    Last Post: 03-22-2009, 12:27 PM
  2. Free Book Suggestions!
    By valaris in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 10-08-2008, 10:25 AM
  3. Hi, Suggestions on my program please..
    By Siggy in forum C++ Programming
    Replies: 44
    Last Post: 11-23-2004, 10:55 PM
  4. Need Suggestions
    By Drew in forum C++ Programming
    Replies: 3
    Last Post: 09-18-2003, 05:46 AM
  5. Suggestions.
    By Shadow in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 02-06-2002, 12:21 PM