Home > Net >  Assign a char* null pointer to an array of characters
Assign a char* null pointer to an array of characters

Time:11-21

I'm trying to assign a (char*)0 pointer to a string in C, but it doesn't work... Here is my code: `

char* token = strtok(command, " ");
        int counter = 0;
        while (token) {
            if(counter == 0){
                strcpy(req.command, token);
            }
            
            printf("Token: %s\n", token);
            strcpy(req.arguments[counter], token);
            counter  ;

            token = strtok(NULL, " ");
        }

        // strcpy(req.arguments[counter], "\0");
        printf("Ok\n");
        req.arguments_size = counter;
        req.arguments[counter] = (char)* 0;

The req structure is this:

typedef struct {
    char command[LENGTH];
    char *const arguments[LENGTH];
    int arguments_size;
} Request;

`

I'm doing this because I want to use execv() function on a server and I need that there is a (char*) 0 after the command arguments in the array. Thank you for your help!

I tried to assign the pointer to the array element in different ways, but it doesn't work and i can't use strcpy because arguments must be not null!

Here it is what the compiler says to me: client-1.c:55:32: error: assignment of read-only location

client-1.c:55:32: error: assignment of read-only location ‘req.arguments[counter]’ 55 | req.arguments[counter] = zero; | ^

CodePudding user response:

You declared an array of constant pointers

char *const arguments[LENGTH];

First of all the array shall be initialized when an object of the structure type is defined and then you may not change elements of the array.

Maybe instead you mean

const char * arguments[LENGTH];

Secondly you need to allocate dynamically memory for stored strings that will be pointed to by elements of the array if you want to copy strings. Otherwise this statement

strcpy(req.arguments[counter], token);

will invoke undefined behavior. For example

req.arguments[counter] = malloc( strlen( token )   1 );
strcpy(req.arguments[counter], token);

Also instead of this statement

req.arguments[counter] = (char)* 0;

it will be simpler and clear to write

req.arguments[counter] = NULL;

CodePudding user response:

The right-hand side of this assignment:

req.arguments[counter] = (char)* 0;

contains a syntax error. You want either (char *)0 or just NULL.

In addition you need to remove the top-level const qualifier from the arguments field, ie const char * arguments[LENGTH]; not char * const arguments[LENGTH];

  • Related