Christopher Tan Christopher Tan - 3 months ago 15
C Question

C array pointer segmentation fault

I'm not familiar to pointers and I stumbled upon segmentation fault on my code, wheres if I don't use pointers this code runs perfectly.

#include <stdio.h>
#include <string.h>

int main()
{

char *string[100],i,j;
char *(*odd)[100];
i = j = 0;

fgets(*string, 100, stdin);

while (*string[i] != '\0') {
if (i % 2 == 0) {
*odd[j++] = string[i];
}
i++;
}

*odd[j] = '\0';

printf("Characters at odd position: %s\n",*odd[j]);

return 0;
}


I'm guessing that I'm printing the
odd
array the wrong way, but I can't print it just using
*odd
as well.

Answer

With pointer:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SIZEOF_BUFFER 100

int main(){ 
    char *string; // string is a pointer
    char i,j;

    char *odd; // odd is a pointer

    // allocate memory to be able to store data
    string = malloc(sizeof(char) * SIZEOF_BUFFER);

    if (string == NULL) {
        exit(-1);
    }

    odd = malloc(sizeof(char) * SIZEOF_BUFFER);

    if (od == NULL) {
        free(string);
        exit(-1);
    }

    i = j = 0;

    fgets(string, SIZEOF_BUFFER, stdin);

    while (string[i] != '\0') {
        if (i % 2 == 0) {
                odd[j++] = string[i];
        }
        i++;
    }

    odd[j] = '\0';

    printf("Characters at odd position: %s\n",odd);

    // Don't forget to free allocated memory
    free(odd);
    free(string);

    return 0;
}

Without pointer:

#include <stdio.h>
#include <string.h>

int main(){ 
    char string[100],i,j;

    char odd[100];

    i = j = 0;

    fgets(string, 100, stdin);

    while (string[i] != '\0') {
        if (i % 2 == 0) {
                odd[j++] = string[i];
        }
        i++;
    }

    odd[j] = '\0';

    printf("Characters at odd position: %s\n",odd);

    return 0;
}

also, no need of *string[strlen(*string) - 1] = '\0'; => fgets put always a null character at the end of string

Comments