简体   繁体   中英

Segmentation fault passing an address specifically defined as a string

Here's more code I whipped up since i was having trouble with my major program that I now fixed.

I have a function which modifies a series of bytes. In this example, the function is supposed to fill up the first 9 bytes of the char array with the numbers 1 through 9 consecutively.

Two tests are run. The first one is calling the function where the parameter is (char*)&myvar . The second test only uses myvar as a parameter. I thought I always had to use an & in front of a char array pointer when I want the string returned in the parameter portion of the function.

Why does this program only work when I don't prepend (char*)& to my char array variable?

When I do apply it, I receive a segmentation fault.

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int func(char* abc){
    char *p=abc;
    int n;
    for (n=1;n<10;n++){
    *p=(unsigned char)(n+48);p++;
    }
    return 0;
}

int main(){
    char vars[1000]="234";
    char *myvar=vars;

    printf("Function test\n");
    int result=func((char*)&myvar); //causes segfault
    printf("Function result %s\n",myvar); //segfault here

    printf("Function test again\n");
    int result2=func(myvar);        //works
    printf("Function result %s\n",myvar);

    printf("DONE\n");
    return 0;
}

Why does this program only work when I don't prepend (char*)& to my char array variable?

Because doing that is completely wrong and not a thing that makes sense.

I thought I always had to use an & in front of a char array pointer when I want the string returned in the parameter portion of the function.

You don't. (Also, you do not have a "char array pointer", and "when I want the string returned in the parameter portion of the function" doesn't make sense.)

When you need to pass a char * to a function that takes a char * , you do not need to put any special prefix in front of the pointer. You just pass it directly, the way you did with

int result2=func(myvar);

You could also have passed in vars , due to the automatic conversion from an array to a pointer to its first element, just like you were able to do char *myvar=vars; without any special casting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM