-2

i'm attempting to use pointers to pass an array of string to and back from a function, or more specifically initializing an array of strings in the main function and using another function to define said array. The issue being that I'm using a for loop to assign a string to an array index, and when the index is larger than 20, (and in turn the for loop) it stops responding. It works fine when its less than or equal to 20.

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

#define MAX 21
#define MAXA MAX+1
#define SIZEAR 6

void col(int *pgv,char **sizev,int *coffv,int *moffv,int *yoffv) {
    for (int i=0;i<MAX;i++) {
        int m=i%2;
        //Size
        if (m==0)
            strcpy(sizev[i],"Small");
        else
            strcpy(sizev[i],"Large");
    }
}

int main(void) {
    int i,pg[MAXA],coff[MAXA],moff[MAXA],yoff[MAXA];//seen

    char **size = (char**)malloc(MAXA*sizeof(char*));
    for(i=0;i<MAXA;i++)
        size[i]=(char*)malloc(SIZEAR*sizeof(char));

    col(pg,size,coff,moff,yoff);
    return 0;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Cpaz
  • 3
  • 1
  • 1
    What if you `#define MAXA (MAX+1)`? – Kurt Revis Dec 13 '14 at 21:06
  • Always initialize your arrays (to zero if nothing else) to prevent accidentally attempting to access an uninitialized element. e.g. `int pg[MAXA] = {0};` is sufficient. Though not strictly required, it will save you grief in the long run. For the same reason, consider using `calloc` instead of `malloc`. It will initialize all allocated space to `zero/NULL`. – David C. Rankin Dec 13 '14 at 21:26
  • @DavidC.Rankin: That's bad advice. If you don't do spurious initializations (which the compiler might not be able to optimize away, thus degrading performance), most compilers will in many situations be able to warn about invalid access. – Deduplicator Dec 14 '14 at 13:50
  • I see your point, which doesn't make it **bad advise** it makes it **implementation dependent**, because there are certainly times when initializing array values to zero is the **correct** thing to do. Or are you saying it is **never** proper to initialize arrays? – David C. Rankin Dec 14 '14 at 17:30

1 Answers1

3
#define MAXA MAX+1

That macro is a classic failure due to insufficient parentheses.
See where it is used:

size[i]=(char*)malloc(SIZEAR*sizeof(char));

Which is after macro-expansion:

size[i]=(char*)malloc(MAX + 1*sizeof(char));

As a side-note, sizeof(char) is always 1.
Also, Don't cast the result of malloc (and friends).

Community
  • 1
  • 1
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • Oh, so it was just me not paying attention.. Fair enough :P but in all seriousness thanks, I've been stumped on this for days.. – Cpaz Dec 14 '14 at 16:43