Thread: convert element of char* to a character

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    50

    convert element of char* to a character

    I've got a variable file of type char*, and am trying to iterate through a for loop by doing the following:

    Code:
    int idx;
    for (idx=0; file[idx] != '\0'; idx++) {
      //do some stuff
    }

    The file[idx] part of the stop condition results in the error Segmentation fault (core dumped). I believe that I am not quite understanding something related to indexing and character pointers. Could someone shed some light on this for me? Thanks!

    I notice that couple of test lines preceeding this code:
    Code:
    printf("%c\n", file[0]);
    printf("%c\n", file[0]);
    do seem to be giving expected results. How can i translate file[idx] into a character that i can use in my stop condition?

  2. #2
    Registered User
    Join Date
    Nov 2008
    Location
    INDIA
    Posts
    64

    Thumbs up

    I think you have not allocaetd the memory for the character pointer variable file.If you allocated memory for that variable you will not get segmentation fault.

    Use this,

    Code:
    #include<stdio.h>
    #include<malloc.h>
    #include<string.h>
    main()
    {
     char *file;
     file=malloc(100);
     strcpy(file,"Hello");
    int idx=0;
    for (idx=0; file[idx] != '\0'; idx++) {
            printf("%c",file[idx]);
    }
    }
    Thanks

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    50
    All of this is going on within a function and unfortunately file is a variable for a function parameter. How could I resolve it in this case? Sorry, I probably should have mentioned that.

  4. #4
    Registered User
    Join Date
    Nov 2008
    Location
    INDIA
    Posts
    64
    Post your entire code . It will helpful for others to understand the problem.

  5. #5
    Registered User
    Join Date
    Feb 2010
    Posts
    50
    whoa! The problem was that my function char* parameter variable (which in this particular use case, takes a file passed by the user) was not null terminated. More surprising is that the string was followed by a bunch of private user and system environment info.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Errors including <windows.h>
    By jw232 in forum Windows Programming
    Replies: 4
    Last Post: 07-29-2008, 01:29 PM
  2. about wide character and multiple byte character
    By George2 in forum C Programming
    Replies: 3
    Last Post: 05-22-2006, 08:11 PM
  3. Sorting a 2-dimensional array
    By kmoyle73 in forum C++ Programming
    Replies: 3
    Last Post: 05-05-2004, 01:54 PM
  4. Character handling help
    By vandalay in forum C Programming
    Replies: 18
    Last Post: 03-29-2004, 05:32 PM
  5. Re : convert character into special code
    By Wah in forum C Programming
    Replies: 0
    Last Post: 01-31-2002, 12:55 AM