Passing char[][] as argument

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • krreks
    New Member
    • Oct 2008
    • 22

    #16
    I ended up solving my problem with the following piece of code.

    Code:
    char * fillFileArr(char * buf, int num, int maxLen) {
    	char * arr = (char *)malloc(num*(maxLen+1));
    
    	int word=0, wordPos=0, bufferPos=0;
    	while(word<num && buf[bufferPos]!='\0') {
    		if(buf[bufferPos]=='\n') {
    			arr[(word*(maxLen+1))+wordPos] = '\0';
    			
    			word++;
    			wordPos=0;
    		} else {
    			arr[(word*(maxLen+1))+wordPos++] = buf[bufferPos];
    		}
    		bufferPos++;
    	}
    	
    	return arr;
    }
    
    void printFileArr(char * files, int num, int maxLen, int withIndex, int indexStart) {
    	int i, index=indexStart;
    	for(i=0; i<num; i++) {
    		if(withIndex==1)
    			printf("! [%2d] ", index++);
    		else
    			printf("! ");
    		printf("%s\n", files+((maxLen+1)*i));
    	}
    }
    
    char * getFromFileArr(char * arr, int maxLen, int wantedIndex) {
    	return (arr+((maxLen+1)*wantedIndex));
    }

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #17
      The correct code for allocating a 2D array is:

      Code:
      char (* arr)[maxLen+8] = malloc(num*(maxLen+1));
      Your function should have had a char (*)[maxLen+8] argument plus one argument for the number of maxLen+8 arrays.

      Read this: http://bytes.com/forum/thread772412.html.

      Comment

      Working...