[Solved] How to correct segmentation fault with char * to int conversion


You are confusing pointers with arrays. A pointer just points; declaring a pointer does not reserve memory, it just creates a pointer variable pointing to some undefined place.

Corrected program:

char *recepcao(char *receber) {
    scanf("%s", receber);
    return receber;
}
int conversao(char *string) { int i, j;
    for(i=0; string[i]!='\0'; ++i) {
        continue;
    }
    int var[100];
    int contagem=0;
    for(j=0; j<i-1; ++j) {
        var[j]=(string[j]-'0');
        contagem+=var[j]*pow(10, (i-j-1));
    }

    return contagem;
}
int main() {
    char receber[100];
    printf("%i", conversao(recepcao(receber))); return 0;
}

Update:

Arrays and pointers are used in a very similar manner in C, but they are not the same. When you declare an array, the compiler reserves the required memory:

int a[10], b[10];
a[1] = 1;  // OK
a = b;     // Error!

Element of array is variable, but array name is not. Array name is sort of label, you cannot change its value so that it pointed to another array.

Pointer is variable. When you declare a pointer, the compiler creates it with undefined contents (like any other variable).

int *p, *q;
p = q;      // OK but useless because both the pointers contain junk addresses
a[0] = *p;  // Depending on where p points you will get either junk in a[0] or memory access violation
. . . 
p = a;                 // Now you can use p as a synonym for array a declared above
if (*(p + 1) == a[1])  // Always true
if (p[2] == *(a + 2))  // Always true
. . .
b = p;   // This won't work; can't assign a new value to array name b
. . .
q = (int*)malloc(sizeof(int) * 10); // Another way of creating int array of 10 elements
q = p;  // Array created with malloc is lost because nothing points to it now

Basically, the only difference between pointers and arrays is that pointer is variable and array name is not. You can’t write “a = p” exactly as you can’t write “2 = i”.

There also is a rather confusing quirk with array as a formal argument:

   void xyz(int a[10]) {
       . . .
   }

   void main() {
       int b[20];
       . . .
       xyz(b);
   }

Looks like we assign b to a, and change array size, right? No, “int a[10]” is treated as “int *a”, and sizeof(a) will return the size of the pointer, not the size of the array.

6

solved How to correct segmentation fault with char * to int conversion