Thread: Help with 2D array

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    2

    Help with 2D array

    Here is the code:

    I'm trying to write a program and running into some problem with the array.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main (int argc, char ** argv)
    {
    	unsigned long numberN = strtoul(argv[1],NULL,10);
    	char** storage = (char**) malloc(10*sizeof(char*));
    	char* current = calloc((numberN+1),sizeof(char*));
    	int item = 0;
    	int c;
    	while (c != EOF)
    	{
    		int n = 0;
    		while (n < numberN && c != EOF)
    		{
    			c = getchar();
    			if (c == EOF)
    				current[n] = '\0';
    			else
    				current[n] = c;
    			n++;
    		}
    		storage[item] = current;
    		char a = '0' + item;
    		putchar(a);
    		putchar(storage[item][0]);
    		putchar(storage[0][0]);
    		item++;
    	}	
    }
    Output: 0aa1bb2cc3dd4
    when input is abcd and numberN is 1.
    Basically, "item" is supposed to increment and as shown by the output it is incrementing but somehow the information is still being stored in storage[0] when item is no longer 0.
    Someone please tell me what is wrong with my code. Much appreciated.

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Code:
    char* current = calloc((numberN+1),sizeof(char*));
    Wrong sizeof there

    Code:
    int c;
    while (c != EOF)
    Using an uninitialized variable there.

  3. #3
    Registered User
    Join Date
    Nov 2009
    Posts
    2
    why is it an invalid size? and it didnt fix the problem. anything else?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. from 2D array to 1D array
    By cfdprogrammer in forum C Programming
    Replies: 17
    Last Post: 03-24-2009, 10:33 AM
  2. Help with mallocing a 2d array please?
    By Gatt9 in forum C Programming
    Replies: 5
    Last Post: 10-10-2008, 03:45 AM
  3. 2D array pointer?
    By willc0de4food in forum C Programming
    Replies: 4
    Last Post: 04-23-2006, 08:16 AM
  4. Read file in 2D array
    By Chook in forum C Programming
    Replies: 1
    Last Post: 05-08-2005, 12:39 PM
  5. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM