Navigating a character string array from pointers

This is a discussion on Navigating a character string array from pointers within the C Programming forums, part of the General Programming Boards category; This program loads 6 words into the array "keywords," then segfaults for some reason. Why does it do this? Code: ...

  1. #1
    Registered User
    Join Date
    Jun 2008
    Posts
    54

    Navigating a character string array from pointers

    This program loads 6 words into the array "keywords," then segfaults for some reason. Why does it do this?


    Code:
    #include<stdlib.h>
    
    int main()
    {
    	char** keywords = (char**) calloc(20, sizeof(char));
    	int i = 0;
    	for (i = 0; i < 20; i++)
    		keywords[i] = (char*) calloc(80, sizeof(char));
    	char string[] =
    	{ "Holy cow omg hey haha wow oh jeeze louise lolz." };
    	char* p = NULL;
    	char* c = string;
    	int n = 0;
    
    	p = *(keywords + 0);
    	while (*c)
    	{
    
    		while (!isspace(*c) && *c)
    		{
    			*p++ = *c++;
    		}
    		*p = '\0';
    		if (!*c)
    			break;
    		c++;
    		n++;
    		p = *(keywords + n);
    		printf("%d\r\n", n);
    	}
    
    	for (n = 0; n < 10; n++)
    		printf("%s\r\n", keywords[n]);
    
    	free(keywords);
    	return 0;
    }
    Last edited by Boxknife; 04-16-2009 at 01:17 PM.

  2. #2
    Registered User
    Join Date
    Mar 2009
    Posts
    20
    sorry
    Last edited by xmariux; 04-16-2009 at 01:48 PM.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    20,955
    Better yet, change it to:
    Code:
    char** keywords = calloc(20, sizeof(*keywords));
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Jun 2008
    Posts
    54
    Quote Originally Posted by laserlight View Post
    Better yet, change it to:
    Code:
    char** keywords = calloc(20, sizeof(*keywords));
    This fixes the problem. Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  3. Replies: 4
    Last Post: 03-03-2006, 01:11 AM
  4. String to a character array?
    By Coder87C in forum C++ Programming
    Replies: 18
    Last Post: 05-24-2005, 08:36 PM
  5. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21