[英]problems allocating memory dynamically to char * []
My problem is that my program only register the last word in cad[]:我的问题是我的程序只注册了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"
.例如,想法是如果
cad[1] = "Hello", ...cad[n] = "Yea"
,所有单词都注册在各自的字段中,但是当我printf
时所有的cad
从0
到n-1
所有的cad[i]
只记录最后一个单词"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. word
变量在堆栈上分配,并经过优化以在读取单词的 for 的每个循环中重用。
Having this said, you are overwriting the allocated memory address with the word
's address, so you just discard the allocated memory.话虽如此,您正在用
word
的地址覆盖分配的 memory 地址,因此您只需丢弃分配的 memory。 So every element in cad
will point to the word
address, which will hold the last read word.因此
cad
中的每个元素都将指向word
地址,该地址将保存最后读取的字。
What you need to do is to copy the contents of word in the allocated space by making use of strcpy
function:你需要做的是利用
strcpy
function复制分配空间中word的内容:
strcpy(cad[i], word);
Also, a good practice is to free
your malloc'd memory after finishing using it:此外,一个好的做法是在完成使用后
free
你的 malloc'd memory:
for (int i = 0; i < N; i++)
{
free(cad[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.