web-dev-qa-db-fra.com

Comment copier une chaîne en utilisant un pointeur

Voici un programme que j'ai écrit pour copier une constante de chaîne.

Lorsque le programme est exécuté, il se bloque. Pourquoi cela arrive-t-il ?

#include <stdio.h>

char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char c;
char *l;

main(){
   while((c = *alpha++)!='\0')
       *l++ = *alpha;
   printf("%s\n",l);
}
14
Arabeka

Pour effectuer cette copie manuelle:

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

int main()
{
    char* orig_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char* ptr = orig_str;

    // Memory layout for orig_str:
    // ------------------------------------------------------------------------
    // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
    // ------------------------------------------------------------------------
    // |A|B|C|D|E|F|G|H|I|J|K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z |\0|  --> data
    // ------------------------------------------------------------------------

    int orig_str_size = 0;
    char* bkup_copy = NULL;

    // Count the number of characters in the original string
    while (*ptr++ != '\0')
        orig_str_size++;        

    printf("Size of the original string: %d\n", orig_str_size);

    /* Dynamically allocate space for the backup copy */ 

    // Why orig_str_size plus 1? We add +1 to account for the mandatory 
    // '\0' at the end of the string.
    bkup_copy = (char*) malloc((orig_str_size+1) * sizeof(char));

    // Place the '\0' character at the end of the backup string.
    bkup_copy[orig_str_size] = '\0'; 

    // Current memory layout for bkup_copy:
    // ------------------------------------------------------------------------
    // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
    // ------------------------------------------------------------------------
    // | | | | | | | | | | |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |\0|  --> data
    // ------------------------------------------------------------------------

    /* Finally, copy the characters from one string to the other */ 

    // Remember to reset the helper pointer so it points to the beginning 
    // of the original string!
    ptr = &orig_str[0]; 
    int idx = 0;
    while (*ptr != '\0')
        bkup_copy[idx++] = *ptr++;

    printf("Original String: %s\n", orig_str);   
    printf("Backup String: %s\n", bkup_copy);

    return 0;
}
16
karlphillip

Pour copier des chaînes en C, vous pouvez utiliser strcpy. Voici un exemple:

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

const char * my_str = "Content";
char * my_copy;
my_copy = malloc(sizeof(char) * (strlen(my_str) + 1));
strcpy(my_copy,my_str);

Si vous souhaitez éviter les dépassements de tampon accidentels, utilisez strncpy au lieu de strcpy. Par exemple:

const char * my_str = "Content";
const size_t len_my_str = strlen(my_str) + 1;
char * my_copy = malloc(len_my_str);
strncpy(my_copy, my_str, len_my_str);
15
Vitor Villar

Vous devez allouer de l'espace pour l. Actuellement, il pointe vers un emplacement aléatoire dans la mémoire et si vous essayez d'écrire dans cet emplacement, le système d'exploitation est susceptible de fermer votre application (blocage de AKA). Si vous voulez que votre code fonctionne tel quel, affectez un espace à l avec malloc() ou créez l en tant que tableau de caractères avec suffisamment d'espace pour contenir "ABCDEFGHIJKLMNOPQRSTUVWXYZ" plus le terminateur NULL.

Voir http://cslibrary.stanford.edu/106/ pour une introduction aux pointeurs.

3
lreeder

Copier une chaîne "constant/literal/pointeur"

char *str = "some string thats not malloc'd";
char *tmp = NULL; 
int i = 0; 
for (i = 0; i < 6; i++) {
    tmp = &str[i];
}
printf("%s\n", tmp);

Inversé

char *str = "some stupid string"; 
char *tmp, *ptr = NULL; 
ptr = str;
while (*str) { ++str; } 
int len = str - ptr;
int i = 0;
for (i = len; i > 11; i--) {
    tmp = &ptr[i];
} 
printf("%s\n", tmp); 

tmp = &blah[i] peut être échangé avec tmp = &(*(blah + i)).

0
user5062183

Vous pouvez directement faire le code ci-dessous:

char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *l = alpha;

Si votre code était ci-dessous:

const char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char *l = alpha;

:)

0
Pankaj Kumar Thapa

la fonction cpy prendra deux pointeurs de caractères et le pointeur src pointera vers le caractère initial de src (tableau de caractères) défini dans la fonction principale, et le même pointeur que le pointeur des pointera vers l'emplacement initial de des (tableau de caractères) défini dans le La fonction principale et la valeur de la boucle while du pointeur src attribueront la valeur au pointeur et incrémenteront le pointeur au prochain élément. Cela se produira jusqu'à ce que la boucle rencontrée avec null et sorte de la boucle et que le pointeur soit simplement attribué à zéro après en prenant toutes les valeurs. 

#include<stdio.h>
void cpy(char *src,char *des)
{
     while(*(des++) = *(src++));
     *des = '\0';
}

int main()
{
     char src[100];
     char des[100];
     gets(src);
     cpy(src,des);
     printf("%s",des);
}

Sortie: Image

0
Shadab Eqbal
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 256
int main(void) {
    char *original, *copy, *start; //three character pointers
    original = malloc(sizeof(char) * MAX_LENGTH); //assigning memory for strings is good practice
    gets(original); //get original string from input
    copy = malloc(sizeof(char) * (strlen(original)+1)); //+1 for \0

    start = copy;
    while((*original)!='\0')
       *copy++ = *original++;
    *copy = '\0';
    copy = start;

    printf("The copy of input string is \"%s\".",copy);
    return 0;
}
0
Shail