Thread: confusion with pointers

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    222

    confusion with pointers

    hi

    i have a problem i wish to create an array of pointers to string positions so that when i say string[i] i get the string that starts in the array position i and extends to the end. what i did so far is

    :
    Code:
    int test(int n){
    	 printf("s \n");
    	 char **sarray;
    	 int i;
             sarray = (char **)malloc(n * sizeof(char *));
             char *string = "lhfsadgfbfsdaubsdkj";
             printf("s - \n");
             for(i=0;i<n;i++){
                sarray[i]=string[0] + i;
             }
             printf("s\n");
             for(i=0;i<n;i++){
                printf("%s - ",sarray[i]);
             }
    }
    but the last print gives me a segmentation fault and tried few combinations on how to dereference and print a string but all a get is the random ascii characters

    help

    thank you

    baxy

  2. #2
    Make Fortran great again
    Join Date
    Sep 2009
    Posts
    1,413
    I don't know what you're trying to do exactly, but this is much easier and straightforward IMO:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
    	char *string = "lhfsadgfbfsdaubsdkj";
    	int i, n = strlen(string);
    	for (i = 0; i < n; i++)
    		puts(string + i);
    	return 0;
    }

  3. #3
    Make Fortran great again
    Join Date
    Sep 2009
    Posts
    1,413
    Oh, and here's your problem:

    Code:
    sarray[i]=string[0] + i;
    string[0] returns the character at the beginning of the string, you need to use plain string, which is the address of the char array.

    try:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(void)
    {
         printf("s \n");
         char **sarray;
         int i, n = 10;
             sarray = (char **)malloc(n * sizeof(char *));
             char *string = "lhfsadgfbfsdaubsdkj";
             printf("s - \n");
             for(i=0;i<n;i++){
                sarray[i]=string + i;
             }
             printf("s\n");
             for(i=0;i<n;i++){
                printf("%s - ",sarray[i]);
             }
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointers & dereferencing confusion
    By LanguidLegend in forum C Programming
    Replies: 9
    Last Post: 11-18-2011, 11:31 AM
  2. Confusion With Pointers
    By ObjectWithBrain in forum C Programming
    Replies: 28
    Last Post: 07-14-2011, 11:44 AM
  3. Confusion using pointers
    By kluxy in forum C Programming
    Replies: 10
    Last Post: 03-27-2010, 12:07 AM
  4. Massive Confusion with Pointers
    By guitarist809 in forum C++ Programming
    Replies: 8
    Last Post: 07-22-2008, 04:01 PM
  5. Confusion about pointers
    By rishiputra in forum C Programming
    Replies: 1
    Last Post: 05-01-2003, 04:39 PM