简体   繁体   中英

problems allocating memory dynamically to char * []

My problem is that my program only register the last word in cad[]:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 4

void main()
{
  char *cad[N];

  for(int i=0;i<N;i++)
  {
      char word[100];
      printf("Escribe algo : ");
      scanf("%s",word);
      cad[i] = (char*)malloc((strlen(word)+1)*sizeof(char));
      cad[i] = word;

  }

  for (int i = 0; i < N; i++)
      printf("%s\n",cad[i]); //just print the last word registered
}

For example, the idea is if cad[1] = "Hello", ...cad[n] = "Yea" , all the words are registered in their respective fields, but when I printf all the cad from 0 to n-1 all the cad[i] just record the last word that is "yea" .

What is the problem and how can I solve it?

The word variable is allocated on stack and is optimised to be reused in every loop of the for that reads the words.

Having this said, you are overwriting the allocated memory address with the word 's address, so you just discard the allocated memory. So every element in cad will point to the word address, which will hold the last read word.

What you need to do is to copy the contents of word in the allocated space by making use of strcpy function:

    strcpy(cad[i], word);

Also, a good practice is to free your malloc'd memory after finishing using it:

    for (int i = 0; i < N; i++)
    {
        free(cad[i]);
    }

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