문제

H i am building a basic shell in c and i need to know the size of the array i am populating with user input. Here is the code.

/*
 * Tp1.c
 *
 *  Created on: 25 janv. 2014
 *      Author: shong
 */
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

void cd_handler(int argc, char *argv[]);
int lire(char *chaine, int longueur);
char** init_command(char *str);

int main(int argc, char *argv[]) {

    //printf("La valeur de argc est: %d", argc);
    while(1){
        printf("Log710H2014%>");
        char str[200];
        lire(str, 200);
        char** comms  = init_command(str);
        printf("%s", comms[1]);

        if(strcmp(comms[0], "cd") == 0){
            int commArgsC = sizeof(comms)/sizeof(comms[0]);
            cd_handler(commArgsC, comms);

        }else if (strcmp(comms[0], "exit") == 0){
            exit(0);
        } 
        }
    }
}
void cd_handler(int argc, char *argv[]){
    char cwd[256];
    char * directory;

    if(argc < 2){
        directory  = getenv("HOME");
    }else if (argc == 2){
        directory = argv[1];
    }else{
        exit(1);
    }

    if (chdir(directory) == -1) {
        printf ("chdir failed - %s\n", strerror (errno));
    }else{
        if (getcwd(cwd, sizeof(cwd)) == NULL)
            perror("getcwd() error");
        else
            printf("current working directory is: %s\n", cwd);
    }
}
char** init_command(char* str){
    char ** res  = NULL;
    char *  p    = strtok (str, " ");
    int n_spaces = 0, i;

    while (p) {
        res = realloc (res, sizeof (char*) * ++n_spaces);

        if (res == NULL){
            exit (-1);
        }
        res[n_spaces-1] = p;
        p = strtok (NULL, " ");
    }
    res = realloc (res, sizeof (char*) * (n_spaces+1));
    res[n_spaces] = 0;

    //print the result

    //for (i = 0; i < (n_spaces+1); ++i)
    //printf ("res[%d] = %s\n", i, res[i]);

    //free the memory allocated

    //free (res);
    return res;
}
int lire(char *chaine, int longueur)
{
    char *positionEntree = NULL;

    if (fgets(chaine, longueur, stdin) != NULL)
    {
        positionEntree = strchr(chaine, '\n');
        if (positionEntree != NULL)
        {
            //*positionEntree = '\0'; // On remplace ce caractère par \0
        }
        return 1;
    }
    else
    {
        return 0; // on renvoie 0 s'il y a eu une erreur
    }
}

The problem is that sizeof(comms) always return 8, no matter the number of elements in comm.

도움이 되었습니까?

해결책 2

The behavior sizeof is dependent on what type of variable it is applied to.

If the variable is a pointer, as in the question, sizeof simply evaluates to the size of the pointer type in bytes:

int *y;                      //y points to an int... maybe an array? Who knows?
printf("%d",sizeof(y));      //No idea how y has been allocated. Defaults to sizeof(int*)

If the variable was declared as an array, sizeof returns the size of the entire array. For instance:

int y[4];                     //y is exactly four ints in memory
printf("%d",sizeof(y));       //sizeof knows this, and evaluates to sizeof(int)*4

This is why the sizeof(table)/sizeof(table[0]) would work for an array. However, it does not work pointers as demonstrated above. In short, passing an array as an argument destroys any information regarding how much data is in that array, and you must pass the size separately. This is referred to as "array decay."

The difference between pointers and arrays is very subtle. Most of the time, the two can be used interchangeably, but there are two critical differences:

  1. The difference in the behavior of sizeof as discussed previously.
  2. Arrays cannot be assigned as pointers can. This relates to the fact that they are of constant size. For instance:


char **table;

//table can be assigned different values....

table = NULL;

//...multiples times, if wanted
table = malloc(sizeof(char*)*20);

However,

//table is constant
char *table[20];

//it's individual elements can be assigned as usual...
table[0] = malloc(1);

//...but attempts to change where table points to will fail
table = NULL; //This will cause a compilation error.

다른 팁

comms is a pointer, so on a 64-bit machine it will have a size of 8 bytes. C has no knowledge about the size of what it points to. You'll have to return the size from the function that allocates the storage and keep track of it yourself.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top