Thread: Writing to an int array made with pointers

  1. #1
    Registered User
    Join Date
    Apr 2010

    Writing to an int array made with pointers


    Could someone tell me why the following code is giving the following error?
             int* counts_add;
             int counts[NUM];
             int fts;
             counts_add = (int*)calloc(NUM, sizeof(int));
             for (j = 0; j < NUM; j++) {
                fts = counts[j];       
                *(counts_add + j*sizeof(int)) = fts;
    This counts_add array is generating memory management errors, and when I run valgrind on the program it says "Invalid write of size 4" at the line *(counts_add + j*sizeof(int)) = fts.

    I have identical (I think, I've checked several times) code in this same function except with different variable names and where instead of ints I have chars, and that works fine. So what is wrong with the writing I'm trying to do here?

    Thanks very much,
    Last edited by n00b19; 04-11-2010 at 10:45 AM.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Assuming sizeof(int) is 4 on your system, you are trying to write to counts_add[0], counts_add[4], counts_add[8], ..., counts_add[4*(NUM-1)]. If you intend to go by ones instead of fours, then you should take the four (i.e., the sizeof(int)) out.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    >*(counts_add + j*sizeof(int)) = fts;
    You're way over-complicating the use of pointers.
    Pointers already know how to scale for the data type they point to.

    So you can just do this
    counts_add[j] = counts[j];
    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.

  4. #4
    Registered User
    Join Date
    Apr 2010
    Thanks! tabstop's fix worked.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  2. Replies: 26
    Last Post: 11-30-2007, 03:51 AM
  3. Working with random like dice
    By SebastionV3 in forum C++ Programming
    Replies: 10
    Last Post: 05-26-2006, 09:16 PM
  4. Converted from Dev-C++ 4 to Dev-C++ 5
    By Wraithan in forum C++ Programming
    Replies: 8
    Last Post: 12-03-2005, 07:45 AM
  5. easy if you know how to use functions...
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 01-31-2002, 07:34 AM